Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.dsilchtsk.tut;
- import java.util.concurrent.TimeUnit;
- public class Operations {
- public static void main(String[] args) {
- final Account a = new Account(1000);
- final Account b = new Account(2000);
- try {
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- transfer(a, b, 500);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- transfer(b, a, 300);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void transfer(Account a, Account b, int amount) throws Exception {
- if (a.getBalance() < amount) {
- throw new Exception("NET BABOK");
- }
- System.out.println("Trying to LOCK acc1");
- synchronized (a) {
- System.out.println("Locked acc1");
- TimeUnit.MILLISECONDS.sleep(1000);
- System.out.println("Trying to LOCK acc2");
- synchronized (b) {
- System.out.println("Locking acc2");
- a.withdraw(amount);
- a.withdraw(amount);
- System.out.println("Transfer successful");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement