内容:一个简单的死锁例子,大概的思路:两个线程A和B,两把锁X和Y,现在A先拿到锁X,然后sleep()一段时间,我们知道sleep()是不会释放锁资源的。然后如果这段时间线程B拿到锁Y,也sleep()一段时间的话,那么等到两个线程都醒过来的话,那么将互相等待对方释放锁资源而僵持下去,陷入死锁。flag的作用就是让A和B获得不同的锁。
public class TestDeadLock { public void run() { MyThread mt = new MyThread(); new Thread(mt, "张三").start(); new Thread(mt, "李四").start(); } class MyThread implements Runnable { private Object o1 = new Object(); private Object o2 = new Object(); private boolean flag = true; @Override public void run() { if (flag) { flag = false; synchronized (o1) { System.out.println(Thread.currentThread().getName() + " have o1"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2) { System.out.println(Thread.currentThread().getName() + " have o2"); } } } else { flag = true; synchronized (o2) { System.out.println(Thread.currentThread().getName() + " have o2"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o1) { System.out.println(Thread.currentThread().getName() + " have o1"); } } } } } public static void main(String[] args) { new TestDeadLock().run(); } }