// File: Putter.java
// T Balls : Nov 2001
// Class that implements an object that generates random integers
// and stores then in a Store object
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* 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
*/
public class Putter extends JPanel implements Runnable
{
/**
* 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
*/
public Putter( Store theStoreToUse )
{
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();
}
private Store theStore;
private JButton runToggle = new JButton( "Run" );
private Log log;
private Thread putRunner;
private boolean running;
private Random randomGenerator = new Random();
/**
* 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
*/
public void run()
{
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 )
{}
}
}
}
|