Posted on 2011-10-17 17:28
瘋狂 閱讀(677)
評論(0) 編輯 收藏 所屬分類:
concurrent
Condition(條件) 將 Object 監視器方法(wait
、notify
和 notifyAll
)分解成截然不同的對象,以便通過將這些對象與任意 Lock
實現組合使用,為每個對象提供多個等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和語句的使用,Condition 替代了 Object 監視器方法的使用。
下面解釋下Condition api里面的例子(生產者,消費者):
public class ConditionTest {
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();
}
}
}