// File: Getter.java
// T Balls : Nov 2001
// Class that implements an object that extracts integers
// from a Store object
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* A threaded object that removes integers from a Store object.
* After successfully retrieving an object, the thread sleeps for a variable
* time in the range 1-10 seconds
*/
public class Getter extends JPanel implements Runnable
{
/**
* Constructor
*/
public Getter( 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" );
getRunner.interrupt();
}
}
});
getRunner = new Thread( this, "Getter" );
running = false;
getRunner.start();
}
private Store theStore;
private JButton runToggle = new JButton( "Run" );
private Log log;
private Thread getRunner;
private boolean running;
private Random randomGenerator = new Random();
/**
* The main method of the thread.
*
* Implements the "run-control" and the sleep period
*/
public void run()
{
while( true )
{
if( !running )
{
synchronized( this )
{
while( !running )
{
try
{
wait();
}
catch( InterruptedException ie )
{
}
}
}
}
log.append( "Get a value from the store: " );
int value = theStore.get();
log.append( "" + value + "\n" );
int pause = 1 + randomGenerator.nextInt( 9 );
log.append( "Sleep for " + pause + " seconds\n" );
try
{
getRunner.sleep( 1000*pause );
}
catch( InterruptedException ie2 )
{}
}
}
}
|