小编dgl*_*glo的帖子

Java线程自发地醒来

我有一个Java线程做这样的事情:

while (running) {
    synchronized (lock) {
        if (nextVal == null) {
            try {
                lock.wait();
            } catch (InterruptedException ie) {
                continue;
            }
        }

        val = nextVal;
        nextVal = null;
    }
    ...do stuff with 'val'...
}
Run Code Online (Sandbox Code Playgroud)

在其他地方我设置这样的值:

if (val == null) {
    LOG.error("null value");
} else {
    synchronized (lock) {
        nextVal = newVal;
        lock.notify();
    }
}
Run Code Online (Sandbox Code Playgroud)

偶尔(实际上每两千万次)nextVal将被设置为null.我已经抛出了记录消息,我可以看到执行顺序如下:

  1. thread1将nextVal设置为newVal
  2. thread1调用lock.notify()
  3. thread2从lock.wait()中醒来
  4. thread2将val设置为nextVal
  5. thread2将nextVal设置为null
  6. thread2用val做的东西
  7. thread2调用lock.wait()
  8. thread2从lock.wait()中醒来
    • 没有其他线程调用lock.notify()和thread2没有被中断
  9. thread2将val设置为nextVal(为null)
  10. 等等

我已经明确检查过锁定第二次醒来,它没有被打断.

我在这里做错了吗?

java multithreading thread-safety

6
推荐指数
1
解决办法
883
查看次数

标签 统计

java ×1

multithreading ×1

thread-safety ×1