Content: Avoid deadlocks by acquiring the order of locks. For example: Bank account transfer problem, two user transfer, if the use of general synchronized nesting, it is easy to create deadlocks, now we are similar to the philosopher problem solution: first to obtain the same lock, to qualify for the next. The judgment is to generate the return value of the class's Hashcode () by System.identityhashcode () as a unique identifier, and the same, we add a lock.
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-amo UNT)); This.money-= amount;} public void Credits (int amount) {System.out.println ("after credit" + Amount + "" + This.money + "+" + (this.money+a Mount)); This.money + = amount;} public int Get () {return this.money;}} public class Orderlock {private static final object Tielock = new Object ();p ublic void TransferMoney (Final account Fromacc T, Final account TOACCT, Final int. amount) throws Insufficientresourcesexception {class Helper {public void transfer () thr oWS 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 {Synchron Ized (Tielock) {synchronized (FROMACCT) {synchronized (TOACCT) {new Helper (). Transfer ();}}}} Class MyThread implements Runnable {Private account fromacct;private account toacct;private int amount;public MyThread (Ac Count 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 ("operation failed");}}} public static void Main (string[] args) {Account Fromacct = new account (100); Account Toacct = new account, Orderlock Orderlock = new Orderlock (); Executorservice ThreadPool = Executors.newcachedthreadpool (); for (int i = 0; i < 5; i++) {if ((I & 1) = = 0) threadpo Ol.execute (orderlock.new MyThread (Fromacct, Toacct, ten)); else Threadpool.execute (orderlock.neW MyThread (Toacct, FROMACCT, 10));}}}
Java avoids deadlocks in order of locks