forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLockExample.java
More file actions
44 lines (40 loc) · 1.52 KB
/
DeadLockExample.java
File metadata and controls
44 lines (40 loc) · 1.52 KB
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 com.examplehub.basics.thread;
public class DeadLockExample {
public final Object resourceA = new Object();
public final Object resourceB = new Object();
public static void main(String[] args) {
DeadLockExample deadLockExample = new DeadLockExample();
Runnable runnableA =
() -> {
synchronized (deadLockExample.resourceA) {
System.out.println(Thread.currentThread().getName() + " get resourceA");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is trying to get resourceB");
synchronized (deadLockExample.resourceB) {
System.out.println(Thread.currentThread().getName() + " get resourceB");
}
}
};
Runnable runnableB =
() -> {
synchronized (deadLockExample.resourceB) {
System.out.println(Thread.currentThread().getName() + " get resourceB");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is trying to get resourceA");
synchronized (deadLockExample.resourceA) {
System.out.println(Thread.currentThread().getName() + " get resourceA");
}
}
};
new Thread(runnableA).start();
new Thread(runnableB).start();
}
}