forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLockSolvedExample.java
More file actions
50 lines (46 loc) · 1.67 KB
/
DeadLockSolvedExample.java
File metadata and controls
50 lines (46 loc) · 1.67 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
45
46
47
48
49
50
package com.examplehub.basics.thread;
public class DeadLockSolvedExample {
public Object resourceA = new Object();
public Object resourceB = new Object();
public static void main(String[] args) {
DeadLockSolvedExample deadLockExample = new DeadLockSolvedExample();
Runnable runnableA =
new Runnable() {
@Override
public void run() {
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 =
new Runnable() {
@Override
public void run() {
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();
}
}