死鎖 java實現
阿新 • • 發佈:2018-11-21
public class Test { public static Object deadLock1 = new Object(); public static Object deadLock2 = new Object(); public static void main(String[] args) throws Exception{ Bank bank = new Bank("s001", 1000); // 建立執行緒物件 SaveAccount sAccount = new SaveAccount(bank); DrawAccount dAccount = new DrawAccount(bank); Thread save = new Thread(sAccount); Thread draw = new Thread(dAccount); save.start(); // +100 // save.join(); draw.start(); // -200 // save.join(); // join(): 阻塞別的執行緒,直到執行緒save結束 // draw.join(); System.out.println(bank); } } public class DrawAccount implements Runnable{ Bank bank; public DrawAccount(Bank bank) { this.bank = bank; } @Override public void run() { int i = 0; while (i < 5) { try { bank.drawAccount(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } i++; } } } public class SaveAccount implements Runnable { Bank bank; public SaveAccount(Bank bank) { this.bank = bank; } @Override public void run() { int i = 0; while (i < 5) { try { bank.saveAccount(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } i++; } } } public class Bank { private String account;// 賬戶 private int balance;// 餘額 boolean flag = true;//控制執行緒執行順序 public Bank(String account, int balance) { this.setAccount(account); this.setBalance(balance); } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } @Override public String toString() { return "銀行 [ 賬號:" + account + ", 餘額:" + balance + "]"; } // public synchronized void saveAccount() throws InterruptedException { public void saveAccount() throws InterruptedException { // if (!flag) { // wait(); // } System.out.println("save start"); synchronized (Test.deadLock1) { Thread.sleep(1000); synchronized (Test.deadLock2) { System.out.println("dead lock save"); } } // 獲取當前賬戶的餘額 int balance = getBalance(); // 修改餘額,存100 balance = balance + 100; setBalance(balance); System.out.println("存款後的賬戶餘額:" + balance); // flag = false; // notifyAll(); } public void drawAccount() throws InterruptedException { // if (flag) { // wait(); // } System.out.println("draw start"); synchronized (Test.deadLock2) { Thread.sleep(1000); synchronized (Test.deadLock1) { System.out.println("dead lock draw"); } } // 獲得當前的賬戶餘額 int balance = getBalance(); // 修改餘額,取200 balance = balance - 200; // 修改賬戶餘額 setBalance(balance); System.out.println("取款後的賬戶餘額:" + balance); // flag = true; // notifyAll(); } }