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()
一次只允许一个线程执行,但最终所有线程最终都会执行。
关于java - notifyAll 是否在不检查条件的情况下从循环中删除等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083627/