Java多執行緒12:多執行緒的死鎖
阿新 • • 發佈:2018-12-13
Java執行緒死鎖是一個經典的多執行緒問題,因為不同的執行緒都在等待根本不可能被釋放的鎖,從而導致所有的任務都無法繼續完成。在多執行緒技術中,“死鎖”是必須避免的,因為這會造成執行緒的“假死”。
package unit2; public class Demo11_Run { public static void main(String[] args) { try { DealThread t1 = new DealThread(); t1.setFlag("a"); Thread thread1 = new Thread(t1); thread1.start(); Thread.sleep(100); t1.setFlag("b"); Thread thread2 = new Thread(t1); thread2.start(); } catch (InterruptedException e) { e.printStackTrace(); } } } class DealThread implements Runnable { public String username; public Object lock1 = new Object(); public Object lock2 = new Object(); public void setFlag(String username) { this.username = username; } public void run() { if (username.equals("a")) { synchronized (lock1) { try { System.out.println("username = " + username); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("按lock1->lock2程式碼順序執行了 "); } } } if (username.equals("b")) { synchronized (lock2) { try { System.out.println("username = " + username); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock1) { System.out.println("按lock2->lock1程式碼 順序執行了 "); } } } } }
使用JDK自帶的工具監測是否有死鎖的現象。首先進入CMD工具,再進入JDK的安裝資料夾中的bin目錄,執行jps命令: 得到執行緒Demo11_Run的id值是2228。再執行jstack命令: