/**
 * This program creates a separate thread by implementing the Runnable interface.
 *
 * On csserver:
 * To compile, enter
 *  javac-sun Driver.java
 * To run, enter
 *  java-sun Driver
 *
 * Figure 4.8 with annotations
 *
 * @author Gagne, Galvin, Silberschatz
 * Operating System Concepts  - Seventh Edition
 * Copyright John Wiley & Sons - 2005.
 */


class Sum  // class of object to be shared; just holds an int
{
      private int sum;

      public int get() {
         return sum;
      }

      public void set(int sum) {
         this.sum = sum;
      }
}

class Summation implements Runnable  // the class that can be run in a thread
{
      private int upper;
      private Sum sumValue;

      // construction receives reference to shared object
      public Summation(int upper, Sum sumValue) {
         if (upper < 0)
            throw new IllegalArgumentException();

         this.upper = upper;
         this.sumValue = sumValue;
      }

      // method to be run in the thread
      public void run() {
         int sum = 0;

         System.out.println("Summation thread executing");
         for (int i = 0; i <= upper; i++)
            sum += i;

         sumValue.set(sum);
         System.out.println("Summation thread exiting");
      }
}

public class Driver
{
      public static void main(String[] args) {
         if (args.length != 1) {
            System.err.println("Usage Driver <integer>");
            System.exit(0);
         }

         Sum sumObject = new Sum();  // object that will be shared by passing
                                     // a reference to thread construction
         int upper = Integer.parseInt(args[0]);
                

         System.out.println("Creating Summation thread");
         Thread worker = new Thread(new Summation(upper, sumObject));
         worker.start();  // start the thread running, calls run method implicitly

         try {
            System.out.println("Original thread waiting");
            worker.join();
         } catch (InterruptedException ie) { }

         System.out.println("Threads have joined");
         System.out.println("The sum of " + upper + " is " + sumObject.get());
      }
}
