Skip to content

Commit 18c43a4

Browse files
Program to create deadlock between two threads.
Write a program to create deadlock between two threads. solution provided is using lambda expression to create threads.
1 parent 993cc2f commit 18c43a4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

DeadlockExample.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2+
public class DeadlockExample {
3+
4+
public static void main(String[] args) {
5+
6+
Runnable r1 = () -> {
7+
System.out.println(Thread.currentThread().getName() + " I will attempt to take String lock");
8+
synchronized (String.class) {
9+
System.out.println(Thread.currentThread().getName() + " Hello I have taken lock on String");
10+
try {
11+
Thread.sleep(1);
12+
} catch (InterruptedException e) {
13+
e.printStackTrace();
14+
}
15+
System.out.println(Thread.currentThread().getName() + " I will attempt to take Integer lock");
16+
synchronized (Integer.class) {
17+
System.out
18+
.println(Thread.currentThread().getName() + " Now I have taken a lock on Integer as well");
19+
}
20+
21+
}
22+
23+
};
24+
25+
new Thread(r1).start();
26+
27+
Runnable r2 = () -> {
28+
System.out.println(Thread.currentThread().getName() + " I will attempt to take Integer lock");
29+
synchronized (Integer.class) {
30+
System.out.println(Thread.currentThread().getName() + " Hello I have taken lock on Integer");
31+
try {
32+
Thread.sleep(1000);
33+
} catch (InterruptedException e) {
34+
e.printStackTrace();
35+
}
36+
System.out.println(Thread.currentThread().getName() + " I will attempt to take String lock");
37+
synchronized (String.class) {
38+
System.out.println(Thread.currentThread().getName() + " Now I have taken a lock on String as well");
39+
}
40+
41+
}
42+
43+
};
44+
45+
new Thread(r2).start();
46+
47+
}
48+
49+
}

0 commit comments

Comments
 (0)