1 package 多线程练习.锁学习;
2
3 /*
4 两个线程互相抱对方想要的锁 都在等待对方释放锁 所以卡死了
5 */
6 public class 自定义死锁 {
7 public static void main(String[] args) {
8 Runnable lileilei = new MakeUp(0, "李蕾蕾");
9 Runnable hanmeimei = new MakeUp(0, "韩梅梅");
10 new Thread(lileilei).start();
11 new Thread(hanmeimei).start();
12 }
13 }
14
15 // 口红
16 class LipStick {
17 }
18
19 // 镜子
20 class Mirror {
21 }
22
23 class MakeUp implements Runnable {
24
25 // 保证独一份口红跟镜子
26 static LipStick lipStick = new LipStick();
27 static Mirror mirror = new Mirror();
28 int choice;
29 String grilName;
30
31 public MakeUp(int choice, String grilName) {
32 this.choice = choice;
33 this.grilName = grilName;
34 }
35
36 @Override
37 public void run() {
38
39 if (choice == 0) {
40
41 synchronized (lipStick) {
42 System.out.println(grilName + "拿到了口红,接着他要拿镜子");
43 try {
44 Thread.sleep(2000);
45 } catch (InterruptedException e) {
46 e.printStackTrace();
47 }
48 synchronized (mirror) {
49 System.out.println(grilName + "拿到了镜子");
50 }
51 }
52 } else {
53
54 synchronized (mirror) {
55 System.out.println(grilName + "拿到了镜子,接着他要拿口红");
56 try {
57 Thread.sleep(2000);
58 } catch (InterruptedException e) {
59 e.printStackTrace();
60 }
61 synchronized (lipStick) {
62 System.out.println(grilName + "拿到了口红");
63 }
64 }
65 }
66
67
68 }
69 }
两个线程互相抱对方想要的锁 都在等待对方释放锁 所以卡死了