/**
  * Encapsulates two threads sharing a sum variable to which both add
  * numbers repeatedly.  No attempt is made to prevent lost updates,
  *
  */
public class IntensiveSumRC implements Runnable {
   // The two fields below are shared by both threads since
   // there is only ONE object created from this class ans associtaed to 2 different threads;
   // note `volatile' is needed in the sum variable declaration due to
   // its interleaved read-update-write accesses by two threads;
   // `volatile' prevents register and CPU-cache caching of variables.
   /**
	 * The number of times to call the summation function.
	 */
   private int N = 0;
   /**
	 * The variable to which the two threads add numbers repeatedly.
	 */
   private volatile long sum = 0;

   /**
	 * Constructor.
	 * @param N The number of times to call the summation function.
	 */
   public IntensiveSumRC(int N) { this.N = N; }

   /**
	 * The summation function simulates a CPU-intensive addition operation.
	 * @param j The initial value.
	 * @param k The number of times to loop.
	 * @return The total
	 */
   private long fn(long j, int k) {
	  long total = j;
	  for (int i = 1;  i <= k; i++) total += i;
	  return total;
   }

   /**
	 * Code for threads inside this object to execute.
	 */
   public void run() {
	  for (int m = 1; m <= N; m++) 
	  	sum = fn(sum, m);
	  System.out.println("sum = " + sum);
   }
}




