// Copyright © 2002 // John M. Thompson // Boulder, Colorado USA // jt@iwaytechnology.com // http://www.iwaytechnology.com // // A limited right to copy this page for // individual (non-commercial) educational // use only is hereby granted. import iwaypublishing.util.IThreadTerminationMonitor; import java.io.PrintWriter; /*********************************************************************** * WorkerThread works at its responsibilty and periodically sleeps * to */ public class WorkerThread extends iwaypublishing.util.IThreadTerminationMonitor { /** A unique name for this thread */ private String name_; public String name(){ return name_; } /** How long to sleep (simulating work) */ private int sleepMillis_ = 1000; /** How many simulated work units done? */ private int workUnits_ = 0; public int workUnits(){ return workUnits_; } /** Where 'proof of work' goes */ private PrintWriter out_ = null; // Optional upper bound on processing iterations // (demonstration purposes only, not required). private static final int INTERNAL_MAX_COUNT = 100000; /******************************************************************/ public WorkerThread( String threadName, int sleepMillis, PrintWriter out ) { super(); // Base class ctor name_ = threadName; sleepMillis_ = sleepMillis; out_ = out; } /******************************************************************/ public void run() { int count = 0; // Do critical, uninterruptable work ;-) while( count++ < INTERNAL_MAX_COUNT ) { synchronized( out_ ) { out_.println( name_ + " started work unit " + name_ + "-" + ++workUnits_ ); } // Do important work (sleep to simulate passage of time) try { Thread.sleep( sleepMillis_ ); } catch( InterruptedException e ){ return; } synchronized( out_ ) { out_.println( name_ + " finished work unit " + name_ + "-" + workUnits_ ); } // Now would be an excellent time to see - // Is it Time To Go? if( terminateUponWakeup() ) { System.out.println( "WorkerThread " + name_ + " terminated." ); return; } } System.out.println( "WorkerThread " + name_ + " finished - returning from run()." ); return; } }