java-notifyAll是否从循环中删除等待而不检查条件?

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

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...