I have some trouble understanding the concept of deadlock situation in this program.
I am getting the output as :
Entered amethod
Entered bmethod
and then the deadlock situation occurs.
Now since my amethod is a synchronized method, shouldn’t it execute first completely i.e. by calling bsum method and then start the new thread. ?
Please explain…
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);
}
}
actually you have started both the threads… lets call the threads 1 and 2
so what happens is when thread 1 acquired the lock over object A and calls the method amethod at the same time
thread 2 has acquired the lock over object B and called the bmethod.
now A wants to call the b’s sum method that is locked because B has already the lock over the object B.
and B wants to call the sum method of A where A has already got the object of A and its not releasing the lock until its done with the calling of sum method.
just remove the synchronized keyword from the sum methods and it will work( i mean not go into deadlock condition)