(百度百科) 死鎖是指兩個或兩個以上的進程在執行過程當中,因爲競爭資源或者因爲彼此通訊而形成的一種阻塞的現象,若無外力做用,它們都將沒法推動下去。此時稱系統處於死鎖狀態或系統產生了死鎖java
public class DeadLock { private static Object lock1 = new Object(); private static Object lock2 = new Object(); public static void main(String[] args) { new Thread(() -> { synchronized (lock1) { sleep(2000); System.out.println("線程1, 等lock2"); synchronized (lock2) { System.out.println("線程1完成"); } } }).start(); new Thread(() -> { synchronized (lock2) { sleep(2000); System.out.println("線程2, 等lock1"); synchronized (lock1) { System.out.println("線程2完成"); } } }).start(); } private static void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }
發現兩個線程都不會打印出"完成", 由於產生了死鎖, 都在等待對方持有的鎖.線程