SOURCE CODE
import java.applet.Applet;
import java.awt.*;
public class SharedCell2 extends Applet {
// show multiple threads modifying shared objects.
// Use synchronization to ensure that both threads access the shared cell properly
private TextArea output;
public void init()
{
output = new TextArea (28, 48);
add (output);
}
public void start ()
{
HoldInteger h = new HoldInteger( );
ProduceInteger p = new ProduceInteger(h, output );
ConsumeInteger c = new ConsumeInteger(h, output );
p.start();
c.start();
}
}
class ProduceInteger extends Thread
{
private HoldInteger pHold;
private TextArea output;
public ProduceInteger ( HoldInteger h, TextArea out)
{
pHold = h;
output = out;
}
// execute the thread
public void run()
{
for ( int count = 0; count < 10; count++)
{
pHold.setSharedInt( count);
output.appendText ("\n Producer set sharedInt to " + count );
// put thread to sleep for a random interval
try
{ sleep( (int) (Math.random() * 3000 ) ); }
catch ( InterruptedException exception )
{ System.err.println ("Exception: " + exception.toString() ); }
}
}
}
class ConsumeInteger extends Thread
{
private HoldInteger cHold;
private TextArea output;
public ConsumeInteger ( HoldInteger h, TextArea out)
{
cHold = h;
output = out;
}
// execute the thread
public void run()
{
int val;
val = cHold.getSharedInt();
output.appendText ("\n Consumer retrieved " + val );
while ( val != 9)
{
// put thread to sleep for a random interval
try
{ sleep( (int) (Math.random() * 3000 ) ); }
catch ( InterruptedException exception )
{ System.err.println ("Exception: " + exception.toString() ); }
val = cHold.getSharedInt();
output.appendText ("\n Consumer retrieved " + val );
}
}
}
class HoldInteger
{
//objects of this class are monitors
private int sharedInt;
private boolean writeable = true; // monitor's condition variable
public synchronized void setSharedInt (int val )
{
while ( !writeable )
{
try
{ wait(); }
catch ( InterruptedException exception )
{ System.err.println ("Exception: " + exception.toString() ); }
}
sharedInt = val;
writeable = false;
notify();
}
public synchronized int getSharedInt ()
{
while ( writeable )
{
try
{ wait(); }
catch ( InterruptedException exception )
{ System.err.println ("Exception: " + exception.toString() ); }
}
writeable = true;
notify();
return sharedInt;
}
}