多線程死鎖:同步中嵌套同步,致使鎖沒法釋放多線程
模擬死鎖的狀況:this
public class TrainThread implements Runnable { // 定義初始化票100張 private int ticketCount = 100; private Object object = new Object(); public boolean flag = true; public void run() { if (flag) { while (true) { synchronized (object) { // 對象鎖 sale(); } } } else { while (true) { sale(); } } } private synchronized void sale() { // this鎖 synchronized (object) { if (ticketCount > 0) { try { Thread.sleep(40); } catch (Exception e) { } System.out.println(Thread.currentThread().getName() + "賣出了第" + (100 - ticketCount + 1 + "張票")); ticketCount--; } } } }
public class App { public static void main(String[] args) throws InterruptedException { TrainThread trainThread = new TrainThread(); //模擬了兩個線程,必須都用同一個Runnable 的子類對象,才能叫 實現資源的共享 Thread thread1 = new Thread(trainThread); Thread thread2 = new Thread(trainThread); thread1.start(); thread1.sleep(40); trainThread.flag = false; thread2.start(); } }
兩個線程,線程1 進入 對象鎖,而後開始sale(),線程1 佔據了this 鎖(會放開),佔據了對象鎖(長期)spa
線程2 進入了sale(),佔據了this 鎖,由於對象鎖被線程1 佔據,因此不能繼續執行,同時由於佔據了this 鎖,線程1 也進入不了,產生死鎖線程