锁类
public class MyLock { public static Object lock_a = new Object(); public static Object lock_b = new Object(); }
线程类
public class DeadLockTest implements Runnable { private boolean flag ; public DeadLockTest(boolean flag) { this.flag = flag; } @Override public void run() { if(flag) { while(true) synchronized(MyLock.lock_a) { System.out.println(Thread.currentThread().getName()+"...lock_a..."); synchronized(MyLock.lock_b) { System.out.println(Thread.currentThread().getName()+"...lock_b..."); } } } else { while(true) synchronized(MyLock.lock_b) { System.out.println(Thread.currentThread().getName()+"...lock_b..."); synchronized(MyLock.lock_a) { System.out.println(Thread.currentThread().getName()+"...lock_a..."); } } } } }
测试代码
import org.junit.Test; public class DeadLock { DeadLockTest a = new DeadLockTest(true); DeadLockTest b = new DeadLockTest(false); Thread t1 = new Thread(a); Thread t2 = new Thread(b); @Test public void TestDeadLock() { t1.start(); t2.start(); } }