1 package demo09; 2 3 //进程死锁 4 public class DeadLockThread implements Runnable { 5 static Object a = new Object(); 6 static Object b = new Object(); 7 private boolean flag; 8 DeadLockThread(boolean flag) { 9 this.flag = flag; 10 } 11 12 public void run() { 13 if (flag) { 14 while (true) { 15 //a锁对象上的同步代码块 16 synchronized (a) { 17 System.out.println(Thread.currentThread().getName()+"a..."); 18 //b锁对象上的同步代码块 19 synchronized (b) { 20 System.out.println(Thread.currentThread().getName()+"b..."); 21 } 22 } 23 } 24 } else { 25 while (true) { 26 //b锁对象上的同步代码块 27 synchronized (b) { 28 System.out.println(Thread.currentThread().getName()+"b..."); 29 //a锁对象上的同步代码块 30 synchronized (a) { 31 System.out.println(Thread.currentThread().getName()+"a..."); 32 } 33 } 34 } 35 } 36 } 37 38 }
1 package demo09; 2 3 public class LockDemo { 4 public static void main(String[] args) { 5 DeadLockThread d1 = new DeadLockThread(true); 6 DeadLockThread d2 = new DeadLockThread(false); 7 8 //创建并开启两个线程 9 new Thread(d1, "线程1").start(); 10 new Thread(d2, "线程2").start(); 11 } 12 }