class A {
synchronized void bar(B b) {
Thread t = Thread.currentThread();
System.out.println("Entered In A "+t);
try{
Thread.sleep(1000);
}
catch(Exception e) {
}
System.out.println("A trying to enter B");
b.last();
}
synchronized void last() {
System.out.println("Inside A last");
}
}
class B {
synchronized void bar(A a) {
Thread t = Thread.currentThread();
System.out.println("Entered In B "+t);
try{
Thread.sleep(1000);
}
catch(Exception e) {
}
System.out.println("B trying to enter A");
a.last();
}
synchronized void last() {
System.out.println("Inside B last");
}
}
class Main {
public static void main(String[] args) {
A a = new A();
B b = new B();
// Thread t1 = new Thread(){
// public void run() {
// a.bar(b);
// }
// };
Thread t2 = new Thread() {
public void run() {
b.bar(a);
}
};
System.out.println("Initialization :");
// t1.start();
a.bar(b);
t2.start();
}
}
您的代码只有在返回 然后t2
调用后,才能启动a.bar(b)
线程。它从不尝试同时调用两个bar()
方法。尝试切换最后两行:先呼叫t2.start()
,然后a.bar(b)
。
如果不起作用,那么可以尝试:
t2.start();
try { sleep(100); } catch {...}
a.bar(b);
主线程中的短sleep()
调用将使t2
线程有更多的启动时间,并实际上进入了b.bar(a)
调用。