SOURCE CODE
import java.applet.Applet;
import java.awt.*;
public class SharedCell1 extends Applet {
// show multiple threads modifying shared object
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
{
private int sharedInt;
public void setSharedInt (int val ) { sharedInt = val; }
public int getSharedInt () { return sharedInt; }
}