【发布时间】:2021-01-10 09:01:12
【问题描述】:
请注意,这不是实际情况。我根据我的实际实现创建了一个示例场景,以便于查看。我也已经得到了预期的输出。但是,我需要澄清一些关于Java 中wait() 和notifyAll() 方法的概念。 (在这里,这两个线程都会在主线程中同时启动 run 方法。)所以据我所知,由于线程 B 处于休眠状态,因为您可以在初始阶段看到 reamingCount 为 400。
所以线程 B 会调用它的 MUTEX.wait() 并继续休眠,直到其他线程调用 notify() 或 notifyAll(),然后在剩余计数减为 0 后,线程 A 将调用 MUTEX.notifyAll(); 唤醒线程 B和MUTEX.wait() 释放它已经授予的锁,并进入睡眠状态,直到线程B通知它。
当我通过线程A调用MUTEX.notifyAll()时,线程B不会在线程A调用MUTEX.wait()之前唤醒并继续其任务吗?
我的意思是,你可以看到当线程 A 调用 MUTEX.notifyAll() 时,线程 B 将唤醒并再次检查 while 循环中的条件是真还是假。因此,由于剩余计数等于 0,线程 B 将退出 while 循环并在线程 A 调用 wait() 之前继续其任务。这种情况不会破坏wait()的原则吗?据我所知,只有当线程A调用wait()时,线程B才能继续执行。
public class A implements Runnable{
public static volatile remainingCount =400;
private final Object MUTEX;//Both class A and B holds the same object mutex
private void methodA(){
synchronized(MUTEX){
while(remainingCount == 0){
MUTEX.notifyAll();
MUTEX.wait();
}
//Perform it's usual task.In here remaining count will decrement during the process.
}
@Override
public void run() {
while(true){
methodA();
}
}
}
}
public class B implements Runnable{
private final Object MUTEX;//Both class A and B holds the same object mutex
private void methodB(){
synchronized(MUTEX){
while (A.remainingCount != 0) {
try {
MUTEX.wait();
} catch (InterruptedException ex) {
Logger.getLogger(InkServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
//incrementing the A.remainingCount
MUTEX.notifyAll();
}
@Override
public void run() {
while(true){
methodB();
}
}
}
【问题讨论】:
标签: java multithreading concurrency java-threads