场景:用户之间相互影响的高并发(如战斗,转账)
借助System.identityHashCode和第三把锁
package com.xinhai.myThread;
public class DealDeadLine {
public void transferMoney(Account a, Account b) {
synchronized (a) {
// 模拟测试
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (b) {
System.out.println("线程锁住 " + Thread.currentThread().getName() + "打印信息");
}
}
}
public void change(Account a, Account b) {
int fromHash = System.identityHashCode(a);
int toHash = System.identityHashCode(b);
if (fromHash > toHash) {
synchronized (a) {
synchronized (b) {
transferMoney(a, b);
}
}
} else if (fromHash < toHash) {
synchronized (b) {
synchronized (a) {
transferMoney(a, b);
}
}
} else {
synchronized (DealDeadLine.class) {
synchronized (a) {
synchronized (b) {
transferMoney(a, b);
}
}
}
}
}
public static void main(String[] args) {
Account a = new Account();
Account b = new Account();
DealDeadLine d = new DealDeadLine();
new Thread(new Runnable() {
@Override
public void run() {
d.change(a, b);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.change(b, a);
}
}).start();
}
}
package com.xinhai.myThread;
public class Account {
}