1 public class Main{ 2 3 /*模拟死锁 4 * 5 * PersonA要拿到B才把A给B 6 * PersonB要拿到A才把B给A 7 * 8 * 9 * 10 */ 11 12 public static void main(String[] args) { 13 new Thread(new Run(true)).start(); 14 new Thread(new Run(false)).start(); 15 } 16 17 } 18 19 class PersonA{ 20 21 public void say(){ 22 System.out.println("A说:把B给我"); 23 } 24 25 public void getB(){ 26 System.out.println("A得到了B的东西"); 27 } 28 } 29 30 class PersonB{ 31 public void say(){ 32 System.out.println("B说:把A给我"); 33 } 34 35 public void getA(){ 36 System.out.println("B得到了A的东西"); 37 } 38 } 39 40 class Run implements Runnable{ 41 42 //一定要是静态的对象 43 static PersonA a = new PersonA(); 44 static PersonB b = new PersonB(); 45 private boolean aGiveB; //是否是A给B 46 47 public Run(boolean aGiveB){ 48 this.aGiveB = aGiveB; 49 } 50 51 @Override 52 public void run() { 53 if(aGiveB){ 54 synchronized (b) { 55 b.say(); 56 try { 57 Thread.sleep(500); 58 } catch (InterruptedException e) { 59 e.printStackTrace(); 60 } 61 synchronized (a) { 62 System.out.println("a把A给了b"); 63 b.getA(); 64 } 65 } 66 }else{ 67 synchronized (a) { 68 a.say(); 69 try { 70 Thread.sleep(500); 71 } catch (InterruptedException e) { 72 e.printStackTrace(); 73 } 74 synchronized (b) { 75 System.out.println("b把B给了a"); 76 a.getB(); 77 } 78 } 79 } 80 } 81 82 }
时间: 2024-10-25 05:21:08