Lecture Videos
  1  import java.util.concurrent.*;
  2  import java.util.concurrent.locks.*;
  3  
  4  public class AccountWithSyncUsingLock {
  5    private static Account account = new Account();
  6  
  7    public static void main(String[] args) {
  8      ExecutorService executor = Executors.newCachedThreadPool();
  9  
 10      // Create and launch 100 threads
 11      for (int i = 0; i < 100; i++) {
 12        executor.execute(new AddAPennyTask());
 13      }
 14  
 15      executor.shutdown();
 16  
 17      // Wait until all tasks are finished
 18      while (!executor.isTerminated()) {
 19      }
 20  
 21      System.out.println("What is balance ? " + account.getBalance());
 22    }
 23  
 24    // A thread for adding a penny to the account
 25    public static class AddAPennyTask implements Runnable {
 26      public void run() {
 27        account.deposit(1);
 28      }
 29    }
 30  
 31    // An inner class for account
 32    public static class Account {
 33      private static Lock lock = new ReentrantLock(); // Create a lock
 34      private int balance = 0;
 35  
 36      public int getBalance() {
 37        return balance;
 38      }
 39  
 40      public void deposit(int amount) {
 41        lock.lock(); // Acquire the lock
 42  
 43        try {
 44          int newBalance = balance + amount;
 45  
 46          // This delay is deliberately added to magnify the
 47          // data-corruption problem and make it easy to see.
 48          Thread.sleep(5);
 49  
 50          balance = newBalance;
 51        }
 52        catch (InterruptedException ex) {
 53        }
 54        finally {
 55          lock.unlock(); // Release the lock
 56        }
 57      }
 58    }
 59  }