// File: Store.java
// T Balls : Nov 2001
// Implement a thread safe integer store for the PutGet problem
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Create and maintain storage for a single integer.
* Protect access to the store using synchronised put and get methods
*/
public class Store extends JPanel
{
/**
* Default constructor.
*
* Create the visual components of the store display
* - a scrolling log area and the current contents of the store
*/
public Store()
{
setLayout( new BorderLayout() );
value = 0;
displayValue = new JLabel( "[ " + value + " ]", JLabel.CENTER );
displayValue.setOpaque( true );
displayValue.setBackground( Color.white );
displayValue.setForeground( Color.red );
displayValue.setFont( new Font( "SansSerif", Font.BOLD, 22 ) );
add( displayValue, BorderLayout.SOUTH );
log = new Log( 30, 20 );
add( log, BorderLayout.CENTER );
}
private int value;
private JLabel displayValue;
private Log log;
/**
* Put a value into the store.
*
* Thread-protected method to put a value into the store
* The calling thread is made to wait if the store is full (!=0)
* The name of the thread is used to identify actions to the on-screen log
*/
public synchronized void put( int valueToPut )
{
log.append( "" + Thread.currentThread().getName() +" to put " + valueToPut );
while( value != 0 )
{
log.append( " - waiting\n" );
try
{
wait();
}
catch( InterruptedException ie )
{}
log.append( "" + Thread.currentThread().getName() +" woken up" );
}
log.append( "\n" );
value = valueToPut;
displayValue.setText( "[ " + value + " ]" );
notifyAll();
}
/**
* Get a value from the store.
*
* Thread-protected method to retrieve a value from the store
* The calling thread is made to wait if the store is empty (==0)
* The name of the thread is used to identify actions to the on-screen log
*/
public synchronized int get()
{
log.append( "" + Thread.currentThread().getName() +" to get value" );
while( value == 0 )
{
log.append( " - waiting\n" );
try
{
wait();
}
catch( InterruptedException ie )
{}
log.append( "" + Thread.currentThread().getName() +" woken up" );
}
log.append( "\n" );
int valueToReturn = value;
value = 0;
displayValue.setText( "[ " + value + " ]" );
notifyAll();
return valueToReturn;
}
}
|