The Java Program: Consistent.java

  1 class Account {
  2 
  3    private int total = 0;
  4 
  5    public synchronized void deposit (int i) { total += i; }
  6                                                  
  7    public synchronized boolean withdraw (int i) {
  8       if (i <= total) {
  9          total -= i;
 10          return true;
 11       }
 12       return false;
 13    }
 14 
 15    public int balance () { return total; }
 16 }
 17 
 18 class Transaction extends Thread {
 19    private static Account accounts [] = new Account [100];
 20    static {
 21       for (int i=0;i<accounts.length;i++) {accounts[i]=new Account();}
 22    }
 23 
 24    private Account a;
 25    Transaction (int no) { a = accounts[no]; }
 26 
 27    public void run () {
 28       synchronized (a) {
 29          // get amount, etc
 30          int d = 100;
 31          // withdraw amount (if possible)
 32          if (a.withdraw(d)) {
 33          }
 34          System.out.println (a.balance());
 35          // dispense receipt, etc
 36       }
 37    }
 38 }
 39 
 40 class Consistent {
 41    public static void main (String args[]) {
 42       new Transaction (3).start();
 43       new Transaction (3).start();
 44    }
 45 }