Home  >  Q&A  >  body text

java - 条件变量的await()释放锁吗?

譬如下面的两个条件变量 isEmpty和isFull
当调用他们的await()时,lock.lock()上的锁会被释放吗?

这里有3个对象,一个i哦是lock,一个是isEmpty,一个是isFull
上锁的对象是lock,而不是isEmpty或者isFull
那isFull或者isEmpty释放的锁确实lock上的?

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
    }       
}
高洛峰高洛峰2763 days ago1414

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-18 10:50:30

    await’s doc has this sentence: The lock associated with this Condition is atomically released

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:50:30

    Thanks for the invitation,
    Answer:

    会;
    是;
    
    The function of

    await() is to allow other threads to access competing resources, so the suspended state is to release the lock of the competing resources. In the java.util.concurrent class library of java
    SE5, the basic class that uses mutual exclusion and allows task suspension is Condition. You can suspend a task through await(). When the external condition changes, it means that a certain The task can continue to execute, and you can notify the task through signal().

    Each lock() call must be followed by a try-finally clause to ensure that the lock can be released under all circumstances. The task must own this lock before it can call await(), signal(), signalAll().

    reply
    0
  • Cancelreply