001package edu.pdx.cs410J.net;
002
003/**
004 * This program starts up a bunch of {@link WorkingThread}s and also
005 * starts an <code>InterruptingThread</code> that will interrupt each
006 * <code>WorkingThread</code> after a given number of seconds.
007 */
008public class InterruptingThread extends Thread {
009  /** The group of threads to interrupt */
010  private ThreadGroup group;
011
012  /** The number of milliseconds to wait before interrupting */
013  private int sleep;
014
015  public InterruptingThread(String name) {
016    super(name);
017  }
018
019  public void run() {
020    System.out.println(this + " sleeping for " + this.sleep + " ms");
021    try {
022      Thread.sleep(this.sleep);
023
024    } catch (InterruptedException ex) {
025      System.err.println("WHY?");
026      System.exit(1);
027    }
028
029    System.out.println(this + " interrupting workers");
030    this.group.interrupt();
031  }
032
033  public static void main(String[] args) {
034    int sleep = Integer.parseInt(args[0]) * 1000;
035
036    ThreadGroup group = new ThreadGroup("Worker threads");
037    for (int i = 0; i < 5; i++) {
038      Thread thread = new WorkingThread(group, "Worker " + i);
039      thread.start();
040    }
041
042    InterruptingThread interrupting = 
043      new InterruptingThread("interrupter");
044    interrupting.group = group;
045    interrupting.sleep = sleep;
046    interrupting.start();
047  }
048
049}