Java — Deadlock | Code Factory

package com.example.thread;/**
* @author code.factory
*
*/
public class DeadlockTest extends Thread {
A a = new A();
B b = new B();

public void m1() {
this.start();
a.a1(b); // This line executed by main Thread
}

public void run() {
b.b1(a); // This line executed by child thread
}

public static void main(String... args) {
DeadlockTest d = new DeadlockTest();
d.m1();
}
}
class A {
public synchronized void a1(B b) {
System.out.println("Thread1 start execution of a1 method");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 trying to call B's test()");
b.test();
}

public synchronized void test() {
System.out.println("Inside A's test() method");
}
}
class B {
public synchronized void b1(A a) {
System.out.println("Thread2 start execution of b1 method");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2 trying to call A's test()");
a.test();
}

public synchronized void test() {
System.out.println("Inside B's test() method");
}
}
Thread1 start execution of a1 method
Thread2 start execution of b1 method
Thread2 trying to call A's test()
Thread1 trying to call B's test()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store