Deadlock is a state where one thread waits for another thread to release a resource and the another thread also waits for some resources. This leads to a situation where the threads will wait for infinite time.
This scenario can be created using java code where an object can be treated a common resource.
Example of deadlock in java:
public class SharedResource {
synchronized void method1(SharedResource sr) {
System.out.println("Method 1");
sr.method2(this);
}
synchronized void method2(SharedResource sr) {
System.out.println("Method 2");
sr.method1(this);
}
}
public class TestMain {
public static void main(String[] args) throws InterruptedException {
SharedResource sc1 = new SharedResource();
SharedResource sc2 = new SharedResource();
Thread t1 = new Thread(() -> {
sc1.method1(sc2);
});
Thread t2 = new Thread(() -> {
sc2.method2(sc1);
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
As you can see in the main method, there are two threads t1 and t2. Both will wait for a common resource to be released by the another thread. But another thread is also waiting for the same resource.
Comments
Post a Comment