1. public class Transfers {2. public static void main(String[] args) throws Exception {3. Record r1 = new Record();4. Record r2 = new Record();5. doTransfer(r1, r2, 5);6. doTransfer(r2, r1, 2);7. doTransfer(r1, r2, 1);8. /*print the result*/9. System.out.println("rl = " + r1.get() +", r2=" + r2.get());10. }11. private static void doTransfer(12. final Record a, final Record b, final int amount) {13. Thread t = new Thread() {14. public void run() {15. new Clerk().transfer(a, b, amount);16. }17. };18. t.start();19. }20. }21. class Clerk {22. public synchronized void transfer(Record a, Record b, int amount){23. synchronized (a) {24. synchronized (b) {25. a.add(-amount);26. b.add(amount);27. }28. }29. }30. }31. class Record {32. int num=10;33. public int get() { return num; }34. public void add(int n) { num = num + n; }35. }