FileDocCategorySizeDatePackage
Putter.javaAPI DocExample2739Tue Nov 13 16:41:20 GMT 2001None

Putter

public class Putter extends JPanel implements Runnable
A threaded object that generates random integers and attempts to store them in an associated Store object. After successfully putting an object, the thread sleeps for a variable time in the range 1-10 seconds

Fields Summary
private Store
theStore
private JButton
runToggle
private Log
log
private Thread
putRunner
private boolean
running
private Random
randomGenerator
Constructors Summary
public Putter(Store theStoreToUse)
Constructor - needs a reference to the Store object to use The Putter class maintains an on-screen log and has a Run/Stop button that can be used to control its actions

      theStore = theStoreToUse;

      setLayout( new BorderLayout() );

      log = new Log( 30, 20 );
      add( log, BorderLayout.CENTER );
      add( runToggle, BorderLayout.SOUTH );

      runToggle.addActionListener( new ActionListener() {
         public void actionPerformed( ActionEvent e )
         {
            if( running )
            {
               running = false;
               runToggle.setText( "Run" );
            }
            else
            {
               running = true;
               runToggle.setText( "Stop" ); 
               putRunner.interrupt();
            }
         }
      });


      putRunner = new Thread( this, "Putter" );
      running = false;
      putRunner.start();
   
Methods Summary
public voidrun()
The main method of the thread. Implements the "run-control" and also the generation of the random number to put and also the sleep period

   
                                      
     
   
      while( true )
      {
         if( !running )
         {
            synchronized( this )
            {
               while( !running )
               {
                  try
                  {
                     wait();
                  }
                  catch( InterruptedException ie )
                  {
                  }
               }
            }
         }
         int valueToPut = randomGenerator.nextInt( 100 );
         log.append( "Put " + valueToPut + " in the store\n" );
         theStore.put( valueToPut );
         int pause = 1 + randomGenerator.nextInt( 9 );
         log.append( "Sleep for " + pause + " seconds\n" );
         try
         {
            putRunner.sleep( 1000*pause );
         }
         catch( InterruptedException ie2 )
         {}
      }