Java通過鎖的順序避免死結,java順序

來源:互聯網
上載者:User

Java通過鎖的順序避免死結,java順序

內容:通過擷取鎖的順序來避免死結。例如:銀行賬戶轉賬問題,兩個使用者轉賬的話,如果採用一般的synchronized嵌套的話,容易造成死結,現在我們通過類似哲學家問題的解決方案一樣:先擷取同一個鎖,才有資格擷取下一個。而判斷是通過System.identityHashCode()來產生類的hashcode()的返回值作為唯一標識,相同的話,我們再加一把鎖。

class Account {private int money;public Account(int money) {this.money = money;}public void debit(int amount) {System.out.println("after debit " + amount + " " + this.money + " -> " + (this.money-amount));this.money -= amount;}public void credit(int amount) {System.out.println("after credit " + amount + " " + this.money + " -> " + (this.money+amount));this.money += amount;}public int get() {return this.money;}}public class OrderLock {private static final Object tieLock = new Object();public void transferMoney(final Account fromAcct, final Account toAcct, final int amount) throws InsufficientResourcesException {class Helper {public void transfer() throws InsufficientResourcesException {if (fromAcct.get() < amount) throw new InsufficientResourcesException();else {fromAcct.debit(amount);toAcct.credit(amount);}}}int fromHash = System.identityHashCode(fromAcct);int toHash = System.identityHashCode(toAcct);if (fromHash < toHash) {synchronized (fromAcct) {synchronized (toAcct) {new Helper().transfer();}}} else if (fromHash > toHash) {synchronized (toAcct) {synchronized (fromAcct) {new Helper().transfer();}}} else {synchronized (tieLock) {synchronized (fromAcct) {synchronized (toAcct) {new Helper().transfer();}}}}}class MyThread implements Runnable {private Account fromAcct;private Account toAcct;private int amount;public MyThread(Account fromAcct, Account toAcct, int amount) {this.fromAcct = fromAcct;this.toAcct = toAcct;this.amount = amount;}@Overridepublic void run() {try {transferMoney(this.fromAcct, this.toAcct, this.amount);} catch (InsufficientResourcesException e) {System.out.println("操作失敗");}}}public static void main(String[] args) {Account fromAcct = new Account(100);Account toAcct = new Account(230);OrderLock orderLock = new OrderLock();ExecutorService threadPool = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {if ((i & 1) == 0)threadPool.execute(orderLock.new MyThread(fromAcct, toAcct, 10));else threadPool.execute(orderLock.new MyThread(toAcct, fromAcct, 10));}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.