forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateDeadlockBetweenTwoThreads.java
More file actions
44 lines (40 loc) · 995 Bytes
/
CreateDeadlockBetweenTwoThreads.java
File metadata and controls
44 lines (40 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package misc;
/**
* Description:-
* Deadlock describes a situation where two or more threads are
* blocked forever, waiting for each other. Deadlocks can occur in Java when the
* synchronized keyword causes the executing thread to block while waiting to
* get the lock, associated with the specified object.
*
*/
public class CreateDeadlockBetweenTwoThreads {
String str1 = "Hello";
String str2 = "World";
Thread t1 = new Thread("First Thread") {
public void run() {
while (true) {
synchronized (str1) {
synchronized (str2) {
System.out.println(str1 + " " + str2);
}
}
}
}
};
Thread t2 = new Thread("Second Thread") {
public void run() {
while (true) {
synchronized (str2) {
synchronized (str1) {
System.out.println(str2 + " " + str1);
}
}
}
}
};
public static void main(String[] args) {
CreateDeadlockBetweenTwoThreads obj = new CreateDeadlockBetweenTwoThreads();
obj.t1.start();
obj.t2.start();
}
}