加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:24:58 所属栏目:Java 来源:网络整理
导读: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()处,

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读