package Model ; // Class which can instantiate objects which can run in separate threads. // We can instantiate an object of this class, // create a new thread, // pass the thread this object, // and run public class SwingWorker extends Object implements Runnable { private int idNum = 0 ; // Object ID. private int counter = 0 ; // Count up. private Thread worker = null ; // Thread for this object. private volatile boolean requestStop = false ; // Request thread stop. public SwingWorker() { } // Construct this object. public SwingWorker( int objectID ) { idNum = objectID ; counter = 0 ; } // All background thread activity happens here. Initiated by model.execute(). public ReturnType doInBackground() { // Periodically check for interrupt signal. while (!requestStop) { System.out.println( "Thread " + idNum + " running. Counter = " + counter ) ; // Catch the exception generated if interrupted during sleep or wait. try { long time = System.currentTimeMillis(); // Spin lock. while ( System.currentTimeMillis() - time < 500 && !requestStop ) { } ++counter ; if (requestStop) { System.out.println( "Thread interrupted during work." ) ; } else { // Sleep int randomTimeMs = (int)(0.5 + 1000.0 * Math.random() ) ; System.out.println( "Thread sleeping " + randomTimeMs + " ms" ) ; worker.sleep( randomTimeMs ) ; } } catch( InterruptedException e ) { // Thread interrupted during sleep or wait. System.out.println( "Thread interrupted during wait/sleep." ) ; } } // end while return (ReturnType) null ; } // Starts a thread executing which runs the function doInBackground(). // returns immediately. void execute() { // Start a thread going on this object. worker = new Thread( this ) ; System.out.println( "Starting new thread..." ); worker.start() ; } // Called when doInBackground() completes. public void done() { System.out.println( "Thread exiting run(), stop = " + requestStop ); } // Run method for the thread. public void run() { doInBackground() ; done() ; } void stop() { System.out.println( "Asking thread to stop..." ); requestStop = true ; worker.interrupt() ; } }