有效的Java Item 72显示了CountDownLatch
实现的错误示例。但它并没有显示出实施它的正确方法。我是否必须使用wait()
和notify()
而不是while
循环?
有谁能建议我这个项目的好例子?
以下是错误的代码示例:
public class SlowCountDownLatch {
private int count;
public SlowCountDownLatch(int count) {
if (count < 0)
throw new IllegalArgumentException(count + " < 0");
this.count = count;
}
public void await() {
while (true) {
synchronized (this) {
if (count == 0)
return;
}
}
}
public synchronized void countDown() {
if (count != 0)
count--;
}
}
答案 0 :(得分:2)
如果你仔细研究那个项目,你会看到这个“线程不应该忙 - 等待,反复检查共享对象等待 发生的事情“这正是在循环中做的坏例子,这就是为什么他也提到了这个”线程应该 如果他们没有做有用的工作就不要跑“。
请参阅以下正确的CountDownLatch实现详细信息:
public class CountDownLatch{
private int count;
/**
* CountDownLatch is initialized with given count.
* count specifies the number of events that must occur
* before latch is released.
*/
public CountDownLatch(int count) {
this.count=count;
}
/**
* Causes the current thread to wait until one of the following things happens-
- latch count has down to reached 0, or
- unless the thread is interrupted.
*/
public synchronized void await() throws InterruptedException {
//If count is greater than 0, thread waits.
if(count>0)
this.wait();
}
/**
* Reduces latch count by 1.
* If count reaches 0, all waiting threads are released.
*/
public synchronized void countDown() {
//decrement the count by 1.
count--;
//If count is equal to 0, notify all waiting threads.
if(count == 0)
this.notifyAll();
}
}