Skip to content

Commit 59bec62

Browse files
committed
死锁的模拟
1 parent f438b45 commit 59bec62

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Multithread/src/T31.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* @program JavaBooks
3+
* @description: 死锁的模拟
4+
* @author: mf
5+
* @create: 2020/01/09 13:57
6+
*/
7+
8+
9+
import java.util.concurrent.ExecutorService;
10+
import java.util.concurrent.Executors;
11+
12+
/**
13+
* 用线程池模拟,比较方便一些
14+
*/
15+
public class T31 {
16+
17+
private static Object res1 = new Object(); // 资源1
18+
19+
private static Object res2 = new Object(); // 资源2
20+
21+
public void m1() {
22+
synchronized (res1) {
23+
// 占用res1的锁
24+
System.out.println(Thread.currentThread().getName() + " get res1");
25+
try {
26+
Thread.sleep(1000); // 延时一会,等待m2的方法占用res2
27+
} catch (InterruptedException e) {
28+
e.printStackTrace();
29+
}
30+
System.out.println("waiting get res2");
31+
synchronized (res2) {
32+
System.out.println(Thread.currentThread().getName() + " get res2");
33+
}
34+
}
35+
}
36+
37+
public void m2() {
38+
synchronized (res2) {
39+
// 占用res2的锁
40+
System.out.println(Thread.currentThread().getName() + " get res2");
41+
try {
42+
Thread.sleep(1000); //
43+
} catch (InterruptedException e) {
44+
e.printStackTrace();
45+
}
46+
System.out.println("waiting get res1");
47+
synchronized (res1) {
48+
System.out.println(Thread.currentThread().getName() + " get res1");
49+
}
50+
}
51+
}
52+
53+
public static void main(String[] args) {
54+
T31 t31 = new T31();
55+
ExecutorService service = Executors.newCachedThreadPool();
56+
service.execute(() -> t31.m1());
57+
service.execute(() -> t31.m2());
58+
}
59+
}

0 commit comments

Comments
 (0)