Java Program To Create DeadLock Between Two Threads
Chapter:
Interview Programs
Last Updated:
14-07-2016 08:01:44 UTC
Program:
/* ............... START ............... */
public class JavaDeadLockExample {
String str1 = "Java";
String str2 = "Scan";
Thread trd1 = new Thread("My Thread 1") {
public void run() {
while (true) {
synchronized (str1) {
synchronized (str2) {
System.out.println(str1 + str2);
}
}
}
}
};
Thread trd2 = new Thread("My Thread 2") {
public void run() {
while (true) {
synchronized (str2) {
synchronized (str1) {
System.out.println(str2 + str1);
}
}
}
}
};
public static void main(String a[]) {
JavaDeadLockExample mdl = new JavaDeadLockExample();
mdl.trd1.start();
mdl.trd2.start();
}
}
/* ............... END ............... */
Output
Notes:
-
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
- Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.
Tags
DeadLock Between Two Threads, Java