线程同步问题
Dabay 2006-12-13 04:13:27 class A{
public B b;
synchronized void methoda(){
String name = Thread.currentThread().getName();
System.out.println(name + " entered class A.methoda().");
try{
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
System.out.println(name + " trying to call B.methodb().");
b.methodb();
}
synchronized void methodb(){
System.out.println("Inside A.methodb().");
}
}
class B{
public A a;
synchronized void methoda(){
String name = Thread.currentThread().getName();
System.out.println(name + " entered class B.methoda().");
try{
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
System.out.println(name + " trying to call A.methodb().");
a.methodb();
}
synchronized void methodb(){
System.out.println("Inside B.methodb().");
}
}
class DeadLock implements Runnable{
A a;
B b;
DeadLock(){
a = new A();
b = new B();
a.b = b;
b.a = a;
Thread.currentThread().setName("MainThread");
new Thread(this).start();
a.methoda();
System.out.println("Over!");
}
public void run(){
Thread.currentThread().setName("RacingThread");
b.methoda();
System.out.println("Back from RacingThread.");
}
public static void main(String[] args){
new DeadLock();
}
}
为什么会出现死锁?2个线程分别调用methoda,然后交叉调用methodb,为什么会死锁呐? 请详细解答 谢谢!!