import java.util.Random;

class Example {
  static Account a = new Account (100);
  static Account b = new Account (100);
  static volatile int u, a1, a2;

  public static void main (String args[]) {
    Thread t1 = new Thread () { 
        public void run () {
          Random r = new Random ();
          while (true) {
            Transaction tx = null;
            try {
              tx = new TSOTransaction ();
              int n = r.nextInt ();
              b.delta (tx, -n);
              a.delta (tx, n);
              tx.commit (); u++;
            } catch (Failure f) {
              tx.abort (); a1++;
            }
          }
        }
      };

    Thread t2 = new Thread () {
        public void run () {
          while (true) {
            Transaction tx = null;
            int total;
            try {
              tx = new TSOTransaction ();
              total = a.read (tx) + b.read (tx);
              tx.commit ();
              System.out.println (
                  "Total=" + total + 
                  " (" + u + "," + a1 +
                  "," + a2 + ")");
            } catch (Failure f) {
              tx.abort (); a2++;
            }
          }
        }
      };

    t1.start ();
    t2.start ();
  }
}
