5

我曾经写过这样的synchronized块:

synchronized(foobar) {
    // do something
}

但是,最近我看到有人写:

synchronized(foobar) {
    // do something
    foobar.notifyAll();
}

foobar.notifyAll();必要吗?如果我省略它会发生什么?

4

4 回答 4

4

简短的回答是这取决于你在做什么。

如果同步块的目标只是确保安全地执行对数据结构的访问/更新,那么notify()或者notifyAll()没有任何用途。

另一方面,如果目标是实现一个“条件变量”,那么notify()ornotifyAll()调用将与这样的调用一起工作wait......例如:

private boolean flag;
private final Object mutex = new Object();

public void awaitFlag(boolean flag) {
    synchronized (mutex) {
        while (this.flag != flag) {
            mutex.wait();
        }
    }
}

public void setFlag(boolean flag) {
    synchronized (mutex) {
        this.flag = flag;
        mutex.notifyAll();
    }
}

上面实现了一个简单的机制,线程调用awaitFlag()等待flag成为trueor false。当另一个线程调用setFlag()更改标志时,当前等待标志更改的所有线程都将被notifyAll(). 这是一个notifyAll()对代码的工作至关重要的示例。


因此,要了解notifyornotifyAll代码是否是必要的,您需要弄清楚是否有其他代码可能会调用wait同一个互斥锁/锁对象。

于 2013-02-12T16:44:09.820 回答
4

You don't need to do this. You only have to do it if the object (here foobar) is waiting to be notified. Notify only Wakes up all threads that are waiting on this object's monitor.

于 2013-02-12T15:58:49.200 回答
2

In Java, you can use wait(), notify() and notifyAll() to achieve thread co-ordination. See How to use wait and notify in Java?

于 2013-02-12T15:59:06.797 回答
1

The notifyAll() is to tell any other thread sleeping in a foobar.wait() that the current thread is about to release the lock and they can compete for the resource again.

于 2013-02-12T15:59:27.860 回答