forked from coding-technology/JavaCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLock.java
More file actions
51 lines (43 loc) · 1.51 KB
/
DeadLock.java
File metadata and controls
51 lines (43 loc) · 1.51 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
51
//本题出现死锁的情况 是一种假设:如果符合预期(A给a加了锁,在等待b;B给b加了锁,在等待a),则会出现死锁;否则,不会。
class AThread implements Runnable{
@Override
public void run() {
synchronized (DeadLock.resource_a) {
System.out.println("A线程:已经给resource-a加了锁");
try {
Thread.sleep((long)(Math.random()*3000) );
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (DeadLock.resource_b){//尝试给B加锁
System.out.println("A线程:等待给resource-b加锁...");
}
}
}
}
class BThread implements Runnable{
@Override
public void run() {
synchronized (DeadLock.resource_b) {
System.out.println("B线程:已经给resource-b加了锁");
try {
Thread.sleep((long)(Math.random()*3000) );
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (DeadLock.resource_a){
System.out.println("B线程:等待给resource-a加锁...");
}
}
}
}
public class DeadLock {
static String resource_a = "resource-a" ;
static String resource_b = "resource-b" ;
public static void main(String[] args) {
Thread A = new Thread(new AThread());
Thread B = new Thread(new BThread());
A.start();
B.start();
}
}