notify,wait,3个以上线程的时候出现的一个问题

HYbdbc HYbdbc 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
首先线程
public class TestThread11 {   
private static Object lock = new Object();
public void execute(){ // synchronized修饰
synchronized(lock){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if(i == 5){
try {
lock.wait();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
}


再来
class ThreadAA implements Runnable {   
public void run() {
TestThread11 test = new TestThread11();
test.execute();
}

public static void main(String[] args)
{
Runnable runabble=new ThreadAA();
Thread a=new Thread(runabble,"A");
a.start();
Thread b=new Thread(runabble,"B");
b.start();
Thread c=new Thread(runabble,"C");
c.start();
}
}


2个线程的时候 还好说一个线程肯定会调用notify,另外一个线程的肯定会被唤醒。
但是如果3个以上的线程时,就有可能线程A 调用wait后,线程B调用notify,然后wait释放锁后,线程A继续运行完,然后会notify线程B继续运行完,在这过程,线程C可能一直都不会运行,但是线程A,B都运行完了,线程Cwait后 就没有线程来唤醒它了,导致死锁。这问题怎么解决?
...全文
评论 3
收藏 已收藏
分享
返回顶部
HYbdbc
Java SE 62,620 成员 307,251 内容