forked from shiyimin/androidtestdebug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLockDemo.java
More file actions
48 lines (42 loc) · 1.02 KB
/
DeadLockDemo.java
File metadata and controls
48 lines (42 loc) · 1.02 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
// 编译命令:
// javac DeadLockDemo.java
//
public class DeadLockDemo {
public static void main(String[] args) {
final Object lock1 = new Object();
final Object lock2 = new Object();
Thread thread1 = new Thread(new Runnable() {
@Override public void run() {
synchronized (lock1) {
System.out.println("线程1获取lock1");
try {
Thread.sleep(50);
} catch (InterruptedException e) {}
synchronized (lock2) {
System.out.println("线程1获取lock2");
}
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override public void run() {
synchronized (lock2) {
System.out.println("线程2获取lock2");
try {
Thread.sleep(50);
} catch (InterruptedException e) {}
synchronized (lock1) {
System.out.println("线程2获取lock1");
}
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {}
System.out.println("程序执行完毕,基本上不会发生!");
}
}