Spurious wakeups, wait() and notifyAll()

泄露秘密 提交于 2019-12-04 12:51:35

The JavaDocs for Object.wait() discuss the spurious wakeup possibility. It also mentions that you should use the wait() in a loop that checks an external condition before leaving the wait loop.

You'll need to restructure the loop() method a bit to accomplish this

private void loop() {
    synchronized (shared) {
        shared.v++;
        while(shared.v < N) {
            shared.wait();
        }

        shared.v = 0;
        synchronized (Q) {
            q.q = true;
        } 
    }

In the end, you should probably find a concurrency library that has this built in since it's easy to get these types of things wrong. I'd look at Google's Guava, java.util.concurrency or one of the many Apache Commons libraries as a starting point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!