Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package org.dsilchtsk.tut;
  2.  
  3. import java.util.concurrent.TimeUnit;
  4.  
  5. public class Operations {
  6.     public static void main(String[] args) {
  7.         final Account a = new Account(1000);
  8.         final Account b = new Account(2000);
  9.  
  10.         try {
  11.             new Thread(new Runnable() {
  12.                 @Override
  13.                 public void run() {
  14.                     try {
  15.                         transfer(a, b, 500);
  16.                     } catch (Exception e) {
  17.                         e.printStackTrace();
  18.                     }
  19.                 }
  20.             }).start();
  21.  
  22.             transfer(b, a, 300);
  23.         } catch (Exception e) {
  24.             e.printStackTrace();
  25.         }
  26.     }
  27.  
  28.     private static void transfer(Account a, Account b, int amount) throws Exception {
  29.         if (a.getBalance() < amount) {
  30.             throw new Exception("NET BABOK");
  31.         }
  32.  
  33.         System.out.println("Trying to LOCK acc1");
  34.         synchronized (a) {
  35.             System.out.println("Locked acc1");
  36.             TimeUnit.MILLISECONDS.sleep(1000);
  37.             System.out.println("Trying to LOCK acc2");
  38.             synchronized (b) {
  39.                 System.out.println("Locking acc2");
  40.                 a.withdraw(amount);
  41.                 a.withdraw(amount);
  42.                 System.out.println("Transfer successful");
  43.             }
  44.         }
  45.  
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement