Condition vs wait notify mechanism

前端 未结 5 1673
遇见更好的自我
遇见更好的自我 2021-01-29 22:17

What is the advantage of using Condition interface/implementations over the conventional wait notify mechanism? Here I quote the comments written by Doug Lea:

5条回答
  •  孤街浪徒
    2021-01-29 22:20

    When you use Condition: await()/signal() you can distinguish which object or group of objects/threads get a specific signal. Here is a short example where some threads, the producers, will get the isEmpty signal while the consumers will get the isFull signal:

    private volatile boolean usedData = true;//mutex for data
    private final Lock lock = new ReentrantLock();
    private final Condition isEmpty = lock.newCondition();
    private final Condition isFull = lock.newCondition();
    
    public void setData(int data) throws InterruptedException {
        lock.lock();
        try {
            while(!usedData) {//wait for data to be used
                isEmpty.await();
            }
            this.data = data;
            isFull.signal();//broadcast that the data is now full.
            usedData = false;//tell others I created new data.          
        }finally {
            lock.unlock();//interrupt or not, release lock
        }       
    }
    
    public void getData() throws InterruptedException{
        lock.lock();
        try {
            while(usedData) {//usedData is lingo for empty
                isFull.await();
            }
            isEmpty.signal();//tell the producers to produce some more.
            usedData = true;//tell others I have used the data.
        }finally {//interrupted or not, always release lock
            lock.unlock();
        }       
    }
    

提交回复
热议问题