The Java Program: Stop.java

  1 // Stop.java -- Avoid stop(), use thread cooperation instead
  2 
  3 public class Stop extends Thread {
  4    private int maxcount, current=0;
  5 
  6    Stop (int maxcount) { this.maxcount = maxcount; }
  7 
  8    public int getCount () { return current; }
  9    public String toString () { return (getName()+" at "+getCount()); }
 10 
 11    private volatile boolean killed=false;  // don't allow copies
 12    public void kill () { killed=true;}
 13    public void killLetDie () { kill(); Thread.yield(); }
 14    public void killAndBlock () throws InterruptedException {
 15       kill(); join();
 16    }
 17 
 18    public void run () {
 19       while (!killed && current<maxcount) {
 20          try {
 21             sleep((int)(Math.random() * 400));
 22          } catch (InterruptedException e) {
 23             // Someone interrupted; just keep on going, but print
 24             // something so the interruption does not silently vanish.
 25             e.printStackTrace();
 26          }
 27          current++;
 28          System.out.println (this);
 29       }
 30       System.out.println ((killed?"KILLED! ":"DONE!   ") + this);
 31    }
 32 
 33    public static void main (String args[]) throws InterruptedException {
 34       Stop [] handle = new Stop [args.length];
 35       for (int i=0; i<args.length; i++) {
 36          handle[i] = new Stop (Integer.parseInt(args[i]));
 37          System.out.printf ("Thread %s: state = %s%n", handle[i], handle[i].getState());
 38          handle[i].start();
 39       }
 40       Thread.sleep (400);  // Give threads a chance to live
 41       for (int i=0; i<handle.length; i++) {
 42          System.out.println ("Killing " + handle[i]);
 43          System.out.printf ("Thread %s: state = %s%n", handle[i], handle[i].getState());
 44          handle[i].killAndBlock();
 45          System.out.printf ("Thread %s: state = %s%n", handle[i], handle[i].getState());
 46          System.out.println ("Killed  " + handle[i]);
 47       }
 48    }
 49 }