public class LeftRightDeadlock { private final Object left = new Object(); private final Object right = new Object(); public void leftRight() { synchronized (left) { synchronized (right) { // doSomething(); } } } public void rightLeft() { synchronized (right) { synchronized (left) { // doSomething(); } } } }
public void transferMoney(Account fromAccount, Account toAccount, DollarAmount anount) throws InsufficientResourcesException { synchronized (fromAccount) { synchronized (toAccount) { if (fromAccount.getBalance().compareTo(amount) < 0) { throw new InsufficientResourcesException(); } else { fromAccount.debit(anount); toAccount.credit(anount); } } } }
private static final Object tieLock = new Object(); public void transferMoney(final Account fromAccount, final Account toAccount, final DollarAmount anount) throws InsufficientResourcesException { class Helper{ public void transfer() throws InsufficientResourcesException { if (fromAccount.getBalance().compareTo(amount) < 0){ throw new InsufficientResourcesException(); } else{ fromAccount.debit(anount); toAccount.credit(anount); } } } int fromHash = System.identityHashCode(fromAccount); int toHash = System.identityHashCode(toAccount); if (fromHash < toHash){ synchronized (fromAccount){ synchronized (toAccount) { new Helper().transfer(); } } } else if (fromHash > toHash){ synchronized (toAccount){ synchronized (fromAccount) { new Helper().transfer(); } } } else { synchronized (tieLock) { synchronized (fromAccount) { synchronized (toAccount) { new Helper().transfer(); } } } } }
class Taxi { private Point location, destination; private final Dispatcher dispatcher; public Taxi(Dispatcher dispatcher) { this.dispatcher = dispatcher; } public synchronized Point getLocation(){ return location; } public synchronized void setLocation(Point location){ this.location = location; if (location.equals(destination)){ dispatcher.notifyAvaliable(this); } } } class Dispatcher { private final Set<Taxi> taxis; private final Set<Taxi> avaliableTaxis; public Dispatcher(){ taxis = new HashSet<Taxi>(); avaliableTaxis = new HashSet<Taxi>(); } public synchronized void notifyAvaliable(Taxi taxi) { avaliableTaxis.add(taxi); } public synchronized Image getImage(){ Image image = new Image(); for (Taxi t :taxis){ image.drawMarker(t.getLocation()); } return image; } }
《Java并发编程实战》第十章 避免活跃性危险 读书笔记,布布扣,bubuko.com
原文:http://blog.csdn.net/love_world_/article/details/27635333