java - notifyAll 是否在不检查条件的情况下从循环中删除等待?

标签 java multithreading wait synchronized notify

public class ShareResource {

private int n = 0;

public synchronized void p() throws InterruptedException {
    while (n > 0) {
    wait();
    }
    n++;
}

public synchronized void r() {
  n = 0;
  notifyAll();
}

}

如果我用这个资源启动了两个线程并且它们都在 wait() 并且我在资源中调用了方法 r() 是否会在不检查条件的情况下唤醒两个线程? 代码是否会被读取到两个线程中的方法结束?在“同一”时间?

最佳答案

Would the code be read until the end of the method in both threads? At the "same" time?

没有也没有。 notifyAll() 的工作原理是每个对象最终wait() 唤醒后执行它们的代码。但是,一次只有一个线程执行。因此,在一个线程通过调用 r() 退出循环后,它会递增计数器,因此不会让另一个线程退出。因此,只有一个线程会执行到最后 - 而不是在两个线程中。

If I started two threads with this resource and they are both at wait() and I called the method r() in the resource would this wake both threads without checking the condition?

我假设您的意思是当您的意思是“不检查条件”时退出 while 循环。如上所示,两个线程都不是这种情况。

TL;DR:notifyAll() 一次只允许一个线程执行,但最终所有线程最终都会执行。

来源:https://stackoverflow.com/a/37046/10869762

关于java - notifyAll 是否在不检查条件的情况下从循环中删除等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083627/

相关文章:

java - 在android中使用jsoup在dom解析器中解析图像

c、创建 child 和wait()

c - 为什么这段带有 fork() 的代码只产生一个输出?

c# - webClient.DownloadDataCompleted 事件

multithreading - F# Winforms 图表异步更新

crash - 在生成的rsync进程上使用等待会停止期望中的rsync

java - 如何获取 TranslateAnimation 中的位置?

java - Glassfish - 获取 session 中的所有队列

java - 使用 XML 属性填充 JComboBox - DOM4J

multithreading - 无限循环是基于目录中文件更改进行处理的最佳解决方案