[英]What is the better way to implement CountDownLatch in effective java 2nd item 72?
Effective Java Item 72 shows bad example of CountDownLatch
implementation. 有效的Java项目72显示了CountDownLatch
实现的错误示例。 But it doesn't show a right way to implement it. 但是它并没有显示实现它的正确方法。 Do I have to use wait()
and notify()
instead of a while
loop ? 我是否必须使用wait()
和notify()
而不是while
循环?
Can anyone suggest me a good example of this item ? 谁能给我推荐这个项目的一个好例子?
Below is the bad code example: 下面是错误的代码示例:
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--;
}
}
If you study carefully that item again , you will see this "Threads should not busy-wait, repeatedly checking a shared object waiting for something to happen" that is exactly what bad example is doing in while loop, that's why he has mentioned this also "Threads should not run if they aren't doing useful work". 如果再次仔细研究该项目,您将看到“线程不应该忙于等待,反复检查共享对象以等待发生的事情”,这正是在while循环中不良示例所做的事情,因此他也提到了这一点“如果线程没有做有用的工作,则它们不应运行”。
See the correct CountDownLatch Implementation details as below: 请参见以下正确的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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.