How to avoid the Deadlock in the below program
Hello Friends,
I am learning java now.I know the following program has deadlock, now i trying the avoid the deadlock for this
program so please post your some suggestions how to avoid the deadlock for the below.
Code :
class A
{
synchronized void foo(B b)
{
System.out.println(Thread.currentThread().getName()+" Entered into A.foo()");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("A Caught Exception");
}
System.out.println(Thread.currentThread().getName()+" Now trying to Access b.last()");
b.last();
System.out.println(Thread.currentThread().getName()+" Now trying to Access b.Info()");
b.info();
}
synchronized void last()
{
System.out.println(Thread.currentThread().getName()+" Entered into A.last()");
}
void msg()
{
System.out.println(Thread.currentThread().getName()+" Entered into A.msg()");
}
}
class B
{
synchronized void bar(A a)
{
System.out.println(Thread.currentThread().getName()+" Entered into B.bar()");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("B Caught Exception");
}
System.out.println(Thread.currentThread().getName()+" Now trying to Access A.last()");
a.last();
System.out.println(Thread.currentThread().getName()+" Now trying to Access A.msg()");
a.msg();
}
synchronized void last()
{
System.out.println(Thread.currentThread().getName()+" Entered into B.last()");
}
void info()
{
System.out.println(Thread.currentThread().getName()+" Entered into B.info()");
}
}
class DeadLockTest2 implements Runnable
{
A a=new A();
B b=new B();
DeadLockTest2()
{
Thread.currentThread().setName("Thread1");
System.out.println(Thread.currentThread().getName()+" Is Now Running");
new Thread(this,"Thread2").start();
System.out.println(Thread.currentThread().getName()+" Is Now Running");
System.out.println(Thread.currentThread().getName()+" is trying to get the lock on A.foo()");
a.foo(b);
System.out.println(Thread.currentThread().getName()+" is got the lock on A.foo()");
nonSyn();
}
public void run()
{
System.out.println(Thread.currentThread().getName()+" Is Now Running");
System.out.println(Thread.currentThread().getName()+" is trying to get the lock on B.bar()");
b.bar(a);
System.out.println(Thread.currentThread().getName()+" is got the lock on B.bar()");
nonSyn();
}
public void nonSyn()
{
a.msg();
b.info();
}
public static void main(String[] args)
{
new DeadLockTest2();
}
}