標籤:style 相等 tar int zed username exce AC span
死結案例:
package com.test;public 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; } @Override public void run() { if (username.equals("a")) { synchronized (lock1) { try { System.out.println("username = " + username); Thread.sleep(3000); } catch (Exception 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 (Exception e) { e.printStackTrace(); } synchronized (lock1) { System.out.println("按 lock2 -> lock1 代碼順序執行了"); } } } }}
package com.test;public class Run { public static void main(String[] args) { try { DealThread d1 = new DealThread(); d1.setFlag("a"); Thread thread1 = new Thread(d1); thread1.start(); Thread.sleep(100); d1.setFlag("b"); Thread thread2 = new Thread(d1); thread2.start(); } catch (Exception e) { e.printStackTrace(); } }}
運行結果:username = ausername = b
死結是程式設計的Bug,在設計程式時就要避免雙方互相持有對方鎖的情況。本案例使用synchronized嵌套的代碼結構來實現死結,其實不適用嵌套的代碼結構也會出現死結。 只要互相等待對方釋放鎖就有可能出現死結。
java 多線程死結