
/here is my sample code for deadlock/
class A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); System.out.println(name + "entered A.foo()"); /*try { //Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("A Interrupted"); }*/ System.out.println("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(InterruptedException e) { System.out.println("B Interrupted"); }*/ System.out.println("Trying to call A.last()"); a.last(); } synchronized void last() { System.out.println("Inside B.last()"); }
} class Deadlock implements Runnable { A a = new A(); B b = new B(); Deadlock() { Thread.currentThread().setName("Main Thread"); Thread t = new Thread(this,"Racing Thread"); t.start(); a.foo(b); System.out.println("Back in Main Thread"); } public void run() { b.bar(a); System.out.println("Back in other thread"); } public static void main(String[] args) { new Deadlock(); }
} My question is that class A has 2 synchronized methods.Object a of class A is calling a.last method .Why it is not entering into last method ??? If class has 2 synchronized methods as in the example if same object of the class calls both the methods will it give access to both of those methods???