I just compiled and run this program of java but the output is unpleasant.
I don’t know why the threads are in deadlock situation.
Can anyone help me to understand the output of the program.
class A {
synchronized void foo(B b) {
String name=Thread.currentThread().getName();
System.out.println(name+"entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {}
System.out.println(name+"trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name=Thread.currentThread().getName();
System.out.println(name+"entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("b interrupted");
}
System.out.println(name+"trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("inside A.last");
}
}
class DeadLock implements Runnable {
A a=new A();
B b=new B();
DeadLock() {
Thread.currentThread().setName("mainthread");
Thread t=new Thread(this,"racingthread");
t.start();
a.foo(b);
System.out.println("back in main thread");
}
public void run() {
b.bar(a);
System.out.println("back in other theread");
}
public static void main(String...d) {
new DeadLock();
}
}
the output on my computer is
mainthreadentered A.foo
racingthreadentered B.bar
mainthreadtrying to call B.last()
racingthreadtrying to call A.last()
You have a classic deadlock.
A.foo()locksaand callsb.last()which attempts to lockbB.bar()locksb1and callsa.last()which attempts to lockaNeither can proceed because each needs the lock of the other.
Because that is what your program is designed to do.
Given you don’t need any of the locks, the simplest solution is to remove all the
synchronizedkeywords.