我不熟悉Java并发。我有一个简单的对象与3个方法,每个对应的代码运行3个不同的线程。为什么notifyAll()语句在这种情况下不会释放其他两个线程中的等待?为什么notifyAll()在这种简单情况下不能恢复其他线程?
public class Main {
static class Obj {
synchronized void t1() {
System.out.println("T1 ran");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
synchronized void t2() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("T2 ran");
}
synchronized void t3() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("T3 ran");
}
}
public static void main(String[] args) {
final Obj o = new Obj();
new Thread(new Runnable() {
@Override
public void run() {
o.t1();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
o.t2();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
o.t3();
}
}).start();
}}
我预计: T1跑 ~~停顿1秒~~ T2跑 T3跑
我: T1跑
真棒谢谢! – 2014-11-08 21:29:31
@其他人:我只用包含方法't1,t2,t3'(Obj1,Obj2,Obj3)的3个不同的“对象”测试源代码 - 结果是相同的。为什么在Obj1上的同步方法会阻止不同的线程分别访问'Obj2.t2'和'Obj3.t3'? – dognose 2014-11-08 21:39:58
啊没关系 - 其他方法已经被发现,但是。 'notifyAll'没有影响,然后:-)所以其他对象线程正在等待,直到黎明:) – dognose 2014-11-08 21:47:16