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



Effective 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--;
    }
}

如果你再次仔细研究该项目,你会看到这个"线程不应该忙等待,反复检查共享对象等待要发生的事情"这正是糟糕的例子在 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();
    }
}

最新更新