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