死锁是两个或更多线程阻塞着等待其它处于死锁状态的线程所持有的锁。死锁通常发生在多个线程同时但以不同的顺序请求同一组锁的时候。
例如,如果线程1锁住了A,然后尝试对B进行加锁,同时线程2已经锁住了B,接着尝试对A进行加锁,这时死锁就发生了。线程1永远得不到B,线程2也永远得不到A,并且它们永远也不会知道发生了这样的事情。为了得到彼此的对象(A和B),它们将永远阻塞下去。这种情况就是一个死锁。
package com.swt.lock; public class Test01 { public static void main(String[] args) throws InterruptedException { Object a = new Object(); Object b = new Object(); new Thread(new SyncThread(a, b)).start(); Thread.sleep(5000); Thread thread = new Thread(new SyncThread(b, a)); thread.start(); thread.join(); } } class SyncThread implements Runnable { private Object a; private Object b; public SyncThread(Object a, Object b) { this.a = a; this.b = b; } @Override public void run() { String name = Thread.currentThread().getName(); System.out.println(name + " 准备获取锁 " + a); synchronized (a) { System.out.println(name + " 已获取锁 " + a); doWork(); System.out.println(name + " 准备获取锁 " + b); synchronized (b) { System.out.println(name + " 已获取锁 " + b); doWork(); } System.out.println(name + " 释放锁 " + b); } System.out.println(name + " 释放锁 " + a); System.out.println(name + " 结束"); } void doWork() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }
输出
Thread-0 准备获取锁 java.lang.Object@68abf112 Thread-0 已获取锁 java.lang.Object@68abf112 Thread-1 准备获取锁 java.lang.Object@1d6bc575 Thread-1 已获取锁 java.lang.Object@1d6bc575 Thread-0 准备获取锁 java.lang.Object@1d6bc575 Thread-1 准备获取锁 java.lang.Object@68abf112