java - 条件变量的await()释放锁吗?
高洛峰
高洛峰 2017-04-18 10:48:30
0
2
1470

譬如下面的两个条件变量 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
    }       
}
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
迷茫

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

Ty80

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().

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template