标签:print 共享 资源 多个 tac 其他 over inter hit
1 package com.thread.syn; 2 3 //死锁:多个线程互相抱着对方需要的资源,然后形成僵持 4 public class DeadLock { 5 public static void main(String[] args) { 6 Makeup g1 = new Makeup(0, "灰姑凉"); 7 Makeup g2 = new Makeup(1, "白雪公主"); 8 9 g1.start(); 10 g2.start(); 11 } 12 } 13 14 //口红 15 class Lipstick { 16 17 } 18 19 //镜子 20 class Mirror { 21 22 } 23 24 //化妆 25 class Makeup extends Thread { 26 27 //需要的资源只有一份,用static来保证只有一份 28 static Lipstick lipstick = new Lipstick(); 29 static Mirror mirror = new Mirror(); 30 31 int choice;//选择 32 String girlName;//使用化妆品的人 33 34 Makeup(int choice, String girlName) { 35 this.choice = choice; 36 this.girlName = girlName; 37 } 38 39 40 @Override 41 public void run() { 42 //化妆 43 try { 44 makeup(); 45 } catch (InterruptedException e) { 46 e.printStackTrace(); 47 } 48 } 49 50 //化妆,互相持有对方的锁,就是互相拿到对方的资源 51 private void makeup() throws InterruptedException { 52 if (choice == 0) { 53 synchronized (lipstick) {//获得口红的锁 54 System.out.println(this.girlName + "获得口红的锁"); 55 Thread.sleep(1000); 56 } 57 synchronized (mirror) {//1s以后获得镜子的锁 58 System.out.println(this.girlName + "获得镜子的锁"); 59 } 60 } else { 61 synchronized (mirror) {//获得镜子的锁 62 System.out.println(this.girlName + "获得镜子的锁"); 63 Thread.sleep(2000); 64 } 65 synchronized (lipstick) {//2s以后想获得口红的锁 66 System.out.println(this.girlName + "获得口红的锁"); 67 } 68 } 69 70 } 71 72 } 73 74 结果: 75 灰姑凉获得口红的锁 76 白雪公主获得镜子的锁 77 灰姑凉获得镜子的锁 78 白雪公主获得口红的锁
标签:print 共享 资源 多个 tac 其他 over inter hit
原文地址:https://www.cnblogs.com/duanfu/p/12260776.html