public void firstThread() throws InterruptedException { Random random = new Random(); for (int i = 0; i < 10_000; i++) { acquireLocks(lock1, lock2); try { Account.transfer(acc1, acc2, random.nextInt(100)); } finally { lock1.unlock(); lock2.unlock(); } } }
public void secondThread() throws InterruptedException { Random random = new Random(); for (int i = 0; i < 10_000; i++) { lock1.lock(); lock2.lock(); try { Account.transfer(acc2, acc1, random.nextInt(100)); } finally { lock1.unlock(); lock2.unlock(); } } }
// When both threads finish execution, finished runs public void finished() { System.out.println("Account 1 balance: " + acc1.getBalance()); System.out.println("Account 2 balance: " + acc2.getBalance()); System.out.println("Total balance: " + (acc1.getBalance() + acc2.getBalance())); }