我在理解这个程序中死锁情况的概念时遇到了一些麻烦。我得到的输出为: Entered amethod Entered bmethod 然后出现死锁情况。现在由于我的方法是一个同步方法,它不应该首先完全执行,即通过调用 bsum 方法然后启动新线程。? 请解释...
public class Deadlock
{
public static void main(String[] args)
{
A a= new A();
B b= new B();
new MainClass1(a,b);
new MainClass2(a,b);
}
}
class MainClass1 extends Thread
{
A a;
B b;
MainClass1(A a,B b)
{
super();
this.a=a;
this.b=b;
start();
}
public void run()
{
a.amethod(b);
}
}
class MainClass2 extends Thread
{
A a;
B b;
MainClass2(A a,B b)
{
super();
this.a=a;
this.b=b;
start();
}
public void run()
{
b.bmethod(a);
}
}
class A
{
public synchronized void amethod(B b)
{
System.out.println("Entered amethod");
try{
Thread.sleep(500);
}catch(Exception e){}
b.bsum(2,3);
}
public synchronized void asum(int a,int b)
{
System.out.println("Sum in A is");
System.out.println(a+b);
}
}
class B
{
public synchronized void bmethod(A a)
{
System.out.println("Entered bmethod");
try{
Thread.sleep(500);
}catch(Exception e){}
a.asum(3, 5);
}
public synchronized void bsum(int a, int b)
{
System.out.println("Sum in B is");
System.out.println(a+b);
}
}