001package edu.pdx.cs410J.net;
002
003import java.util.Random;
004
005/**
006 * This thread will work until and then wait until it is interrupted.
007 */
008public class WorkingThread extends Thread {
009
010  public WorkingThread(ThreadGroup group, String name) {
011    super(group, name);
012  }
013
014  public void run() {
015    Random random = new Random();
016
017    while (true) {
018      // Have I been interrupted?
019      if (this.isInterrupted()) {
020        System.out.println(this + " is done");
021        return;
022      }
023
024      // Do some work
025      int work = Math.abs(random.nextInt(100000));
026      System.out.println(this + " working for " + work);
027      for (int l = 0; l < work; l++);
028
029      // Sleep
030      try {
031        int sleep = random.nextInt(2000);
032        System.out.println(this + " sleeping for " + sleep + " ms");
033        Thread.sleep(sleep);
034
035      } catch (InterruptedException ex) {
036        System.out.println(this + " interrupted while sleeping");
037        return;
038      }
039    }
040  }
041
042}