private static final String LEFT = "left"; private static final String RIGHT = "right"; public static void main(String[] args) throws Exception { Thread deallock1 = new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (LEFT) { synchronized (RIGHT) { System.out.printf("todo1"); } } } } }); Thread deallock2 = new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (RIGHT) { synchronized (LEFT) { System.out.printf("todo2"); } } } } }); deallock1.setName("deallock1"); deallock2.setName("deallock2"); deallock1.start(); deallock2.start(); }
public static void transfer(Account from, Account to, int cash) throws Exception { synchronized (from) { synchronized (to) { from.money -= cash; to.money += cash; } } }
這段代碼看起來很良好,可是若是狀況是兩個線程一個transfer(my, your, cash),另外一個是transfer(your, my, cash)的時候,就會可能產生死鎖。若是可以保證上述的鎖的順序一致的話,就能避免死鎖,有一種方式能夠避免,就是比較對象的hashcode值,而後按照大小順序鎖住:java