在有效的java第2项72中,实现CountDownLatch的更好方法是什么?

在有效的java第2项72中,实现CountDownLatch的更好方法是什么?,java,multithreading,effective-java,countdownlatch,Java,Multithreading,Effective Java,Countdownlatch,有效的Java项目72显示了CountDownLatch实现的错误示例。但它并没有给出一个正确的实现方法。我是否必须使用wait()和notify()而不是while循环 有谁能给我举一个这个项目的好例子吗 下面是错误代码示例: public class SlowCountDownLatch { private int count; public SlowCountDownLatch(int count) { if (count < 0)

有效的Java项目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--;
    }
}
公共类SlowCountDownLatch{
私人整数计数;
公共慢计数下闩锁(整数计数){
如果(计数<0)
抛出新的IllegalArgumentException(计数+“<0”);
this.count=计数;
}
公共空间等待(){
while(true){
已同步(此){
如果(计数=0)
返回;
}
}
}
公共同步无效倒计时(){
如果(计数!=0)
计数--;
}
}

如果您再次仔细研究该项,您将看到“线程不应该忙于等待,而是重复检查共享对象等待 这正是坏例子在while循环中所做的,这就是为什么他也提到了这一点 如果他们没有做有用的工作,就不要运行”

请参见以下正确的倒计时闩锁实现详细信息:

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();
    }
}

你读过
java.util.concurrent.CountDownLatch
的源代码了吗?也许这有帮助。