当线程1拿到锁1的时候,打算进入锁2的代码需要锁2 当线程2拿到锁2的时候,打算进入锁1的代码需要锁1 此时程序卡死!因为线程1需要的2锁在线程2里,同时线程2需要的1锁在线程1里
死锁的实现思路两个锁嵌套
//以下为线程1执行
synchronized(锁定1)
{
synchronized(锁定2)
{
}
}
//以下为线程2执行
synchronized(锁定2)
{
synchronized(锁定1)
{
}
}
package hysy32.MultiThread; /** * Created by 小管 on 2017/4/2. */ public class DeadLockTest { public static void main(String[] args) { LockDemo l = new LockDemo(true); LockDemo l1 = new LockDemo(false); Thread t1 = new Thread(l); Thread t2 = new Thread(l1); t1.start(); t2.start(); } } class LockDemo implements Runnable { private boolean b; public LockDemo(boolean b) { this.b = b; } @Override public void run() { if (b) { while (true) { synchronized (lock.lockA) { System.out.println("true...LockA"); synchronized (lock.lockB) { System.out.println("true...LockB"); } } } } else synchronized (lock.lockB) { while (true) { System.out.println("false...LockB"); synchronized (lock.lockA) { System.out.println("false...LockA"); } } } } } class lock { public static Object lockA = new Object(); public static Object lockB = new Object(); }
1 class Test implements Runnable 2 { 3 private boolean flag; 4 Test(boolean flag) 5 { 6 this.flag = flag; 7 } 8 9 public void run() 10 { 11 if(flag) 12 { 13 while(true) 14 { 15 synchronized(MyLock.LOCKA) 16 { 17 System.out.println(Thread.currentThread().getName()+"...if......locka"); 18 synchronized(MyLock.LOCKB) 19 { 20 System.out.println(Thread.currentThread().getName()+"...if......lockb"); 21 } 22 } 23 } 24 } 25 else 26 { 27 while(true) 28 { 29 synchronized(MyLock.LOCKB) 30 { 31 System.out.println(Thread.currentThread().getName()+"...else......lockb"); 32 synchronized(MyLock.LOCKA) 33 { 34 System.out.println(Thread.currentThread().getName()+"...else......locka"); 35 } 36 } 37 } 38 } 39 } 40 } 41 //定义一个用于存储锁对象类。 42 class MyLock 43 { 44 public static final Object LOCKA = new Object(); 45 public static final Object LOCKB = new Object(); 46 } 47 48 class DeadLockTest 49 { 50 public static void main(String[] args) 51 { 52 //创建两个线程任务。 53 Test t1 = new Test(true); 54 Test t2 = new Test(false); 55 56 Thread t11 = new Thread(t1); 57 Thread t22 = new Thread(t2); 58 t11.start(); 59 t22.start(); 60 61 } 62 }