Condition
Condition是Object裏麵的wait、notify、notifyAll方法的一個替換
Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.
鎖(Lock)替換了synchronized 方法和synchronized 代碼塊,條件(Condition)替換了Object類裏麵的監視器方法如:wait、notify、notifyAll
Condition的await或者signal方法必須在持有鎖的時候調用,即在lock.lock()及lock.unlock()之間調用
如果當前線程沒有持有鎖就去調用Condition的await或者signal方法,將拋出一個IllegalMonitorStateException異常
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
await方法:進入等待狀態
Causes the current thread to wait until it is signalled or interrupted.
調用該方法將會使當前線程進入等待狀態,知道收到signal信號或者被中斷。
如果一個線程進入wait狀態,如下情況能夠喚醒:
一、其他線程調用了signal方法、並且當前線程正好被選中喚醒。
二、其他線程調用了signalAll方法。
三、其他線程中斷了( interrupts)當前線程。
四、發生了偽喚醒。
不管發生上麵的哪一種情況,當前線程都需要重新獲取鎖。
awaitNanos方法:等待指定時間
awaitUninterruptibly方法:進入等待狀態,interrupt對這個等待無效,忽略中斷請求
signal方法:喚醒等待線程中的其中一個
signalAll方法:喚醒所有正在等待的線程
最後更新:2017-04-01 17:04:39