为什么这会在启动时立即陷入死锁 - 它打印一行然后卡住(在建议的编辑之后)?
这可能是因为第一个线程在开始等待之前错过了通知触发器。
分辨率是多少?
public class threadTwo{
AtomicInteger i=new AtomicInteger(0);
Boolean b=new Boolean(false);
class firstThread implements Runnable{
AtomicInteger i;
Boolean b;
firstThread(AtomicInteger i,Boolean b){
this.i=i;
this.b=b;
}
public void run(){
while(true){
synchronized(i){
try{
while(b==false)
i.wait();
if(i.intValue()<30){
i.incrementAndGet();
System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
}
b=false;
i.notify();
}catch(InterruptedException x){}
}
}
}
}
class secondThread implements Runnable{
AtomicInteger i;
Boolean b;
secondThread(AtomicInteger i,Boolean b){
this.i=i;
this.b=b;
}
public void run(){
while(true){
synchronized(i){
try{
while(b==true)
i.wait();
if(i.intValue()<40){
i.getAndAdd(2);
System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
}
b=true;
i.notify();
}catch(InterruptedException x){}
}
}
}
}
void runThread(){
Thread t1 = new Thread(new firstThread(i,b));
Thread t2 = new Thread(new secondThread(i,b));
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){}
System.out.println("Result : " + i.intValue());
}
public static void main(String[] args){
new threadTwo().runThread();
}
}
最佳答案
问题出在 firstThread
中的 b.wait()
。
这个变量 b
永远不会从 secondThread
得到通知,因为 secondThread
在检查 if(b==true)
时失败。 code> 并立即返回。
但也要注意这样一个事实,通过变量 b
进行同步非常糟糕,因为语句
b=false;
和
b=true;
正在将新实例分配给变量,因此 firstThread
和 secondThread
失去连接。
关于java - 初始化时死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952068/