-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadDeadLock.java
62 lines (58 loc) · 1.29 KB
/
ThreadDeadLock.java
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
52
53
54
55
56
57
58
59
60
61
62
package java_thread;
/**
* Dead lock
*
* @author 唐龙
*
*/
public class ThreadDeadLock {
//This is a test
public static void main(String[] args) {
DeadLockThread dlt = new DeadLockThread();
dlt.t1.start();
dlt.t2.start();
}
}
/**死锁类*/
class DeadLockThread extends Thread{
private String s1="AA";
private String s2="BB";
//线程t1
Thread t1 = new Thread(){
@Override
public void run(){
synchronized (s1) {
System.out.println("t1已占有"+s1);
try {
Thread.sleep(1000);//停顿1000秒,另一个线程有足够的时间占有其它资源
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1 试图占有"+s2);
System.out.println("t1 等待中 。。。。");
synchronized (s2) {
System.out.println("do something");
}
}
}
};
//线程t2
Thread t2 = new Thread(){
@Override
public void run(){
synchronized (s2) {
System.out.println("t2 已占有"+s2);
try {
Thread.sleep(1000);//停顿1000秒,另一个线程有足够的时间占有其它资源
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 试图占有"+s1);
System.out.println("t2 等待中 。。。。");
synchronized (s1) {
System.out.println("do something");
}
}
}
};
}