Java Deadlock
In java, a deadlock occurs in a situation when two or more threads are blocked and waiting for each other to release the lock.
A thread waiting for an object lock but it obtained by another thread and another thread is waiting for an object lock but is obtained by the first thread. Both threads are waiting forever for each other to release the lock.

Example:
public class Deadlock{
public static Object obj1 = new Object();
public static Object obj2 = new Object();
private static class Thread1 extends Thread {
public void run() {
synchronized (obj1) {
System.out.println("Thread 1: Holding lock 1");
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread 1: Waiting for lock 2");
synchronized (obj2) {
System.out.println("Thread 1: Holding lock 2");
}
}
}
}
private static class Thread2 extends Thread {
public void run() {
synchronized (obj2) {
System.out.println("Thread 2: Holding lock 2");
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread 2: Waiting for lock 1");
synchronized (obj1) {
System.out.println("Thread 2: Holding lock 1");
}
}
}
}
public static void main(String args[]) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com