标签:dea 演示 lock ati logs pre ble 主程序 sys
1 //写一个死锁程序 2 public class DeadLock { 3 //主程序执行 4 public static void main(String[] args) { 5 Thread thread1 = new Thread(new MyThread(true)); 6 Thread thread2 = new Thread(new MyThread(true)); 7 thread1.start(); 8 thread1.start(); 9 thread2.start(); 10 } 11 } 12 class MyThread implements Runnable{ 13 private boolean flag; 14 //标记,用来分割线程执行部分 15 public MyThread(boolean flag) { 16 this.flag = flag; 17 } 18 @Override 19 public void run() { 20 if (flag) { 21 //线程1拥有锁1而需要锁2 22 synchronized(MyLock.object1) { 23 System.out.println("锁1"); 24 synchronized(MyLock.object2) { 25 System.out.println("锁2"); 26 } 27 } 28 }else { 29 //线程2拥有锁2而需要锁1 30 synchronized(MyLock.object2) { 31 System.out.println("锁2"); 32 synchronized(MyLock.object1) { 33 System.out.println("锁1"); 34 } 35 } 36 } 37 38 } 39 } 40 class MyLock{ 41 //创建两个显式的锁 42 static Object object1 = new Object(); 43 static Object object2 = new Object(); 44 }
标签:dea 演示 lock ati logs pre ble 主程序 sys
原文地址:http://www.cnblogs.com/anzhi/p/7465153.html