Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.concurrent.locks.Condition;
- class ConditionLock {
- public static void main(String[] args) {
- Store1 store = new Store1();
- new Thread(new Producer1(store)).start();
- new Thread(new Consumer1(store)).start();
- new Thread(new Consumer1(store)).start();
- new Thread(new Consumer1(store)).start();
- }
- }
- class Store1 {
- private int product = 0;
- private ReentrantLock locker;
- private Condition conditionPut, conditionGet;
- private boolean stateSales = true;
- Store1() {
- locker = new ReentrantLock();
- conditionPut = locker.newCondition();
- conditionGet = locker.newCondition();
- }
- public void put() {
- try {
- locker.lock();
- while(product >= 3) {
- if(!stateSales) return;
- System.out.println("put...");
- conditionPut.await();
- }
- product++;
- System.out.println("put (1) - count " + product);
- conditionGet.signalAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- locker.unlock();
- }
- }
- public void closeSales() {
- locker.lock();
- try {
- stateSales = false;
- conditionGet.signalAll();
- conditionPut.signalAll();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- locker.unlock();
- }
- }
- public void get() {
- try {
- locker.lock();
- while(product < 1) {
- if(!stateSales) return;
- System.out.println("get...");
- conditionGet.await();
- }
- product--;
- System.out.println("get (1) - count " + product);
- conditionPut.signalAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- locker.unlock();
- }
- }
- }
- class Producer1 implements Runnable{
- Store1 store;
- Producer1(Store1 store){
- this.store=store;
- }
- public void run(){
- for (int i = 1; i < 6; i++) {
- store.put();
- }
- store.closeSales();
- }
- }
- class Consumer1 implements Runnable{
- Store1 store;
- Consumer1(Store1 store){
- this.store=store;
- }
- public void run(){
- for (int i = 1; i < 6; i++) {
- store.get();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement