Please send questions to
st10@humboldt.edu .
// playing with synchronized threads...
//
// recommended size: 200h, 200w
// last modified: 3-26-01
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class TrySync extends Applet implements Runnable, ActionListener
{
Thread readIt, catchIt;
TextField readField;
Label readLabel, catchLabel;
boolean startReadIt;
final Object token = "token";
public void init()
{
setBackground(Color.lightGray);
Label readFieldInstr = new Label("type stuff here: ");
add(readFieldInstr);
readField = new TextField(15);
readField.setText("");
readField.addActionListener(this);
add(readField);
Label readBlurb = new Label("readIt read: ");
add(readBlurb);
readLabel = new Label();
readLabel.setText(" ");
readLabel.setBackground(Color.cyan);
add(readLabel);
Label catchBlurb = new Label("catchIt caught: ");
add(catchBlurb);
catchLabel = new Label();
catchLabel.setText(" ");
catchLabel.setBackground(Color.yellow);
add(catchLabel);
startReadIt = false;
}
public void start()
{
if (readIt == null)
{
readIt = new Thread(this);
readIt.start();
}
if (catchIt == null)
{
catchIt = new Thread(this);
catchIt.start();
}
}
public void run()
{
Thread execThread;
execThread = Thread.currentThread();
while (true)
{
// readIt loops with resource1 locked until
// text entered into readField causes
// startReadIt to be set to true;
if (execThread == readIt)
{
System.out.println("readIt has started");
synchronized(token)
{
System.out.println("readIt has token");
while (startReadIt == false)
{
try
{
// sleep for 1 second (1000 msec = 1 sec)
Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
}
readLabel.setText(readField.getText());
}
System.out.println("readIt has released token");
startReadIt = false;
}
else if (execThread == catchIt)
{
System.out.println("catchIt has started");
// pause catchIt just a little, so it
// doesn't get resource1 before readIt
try
{
// sleep for 1 second (1000 msec = 1 sec)
Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
synchronized(token)
{
// when writeIt gets resource1, it
// is safe to grab the text of readLabel
// and display it on writeLabel
System.out.println("catchIt has token");
catchLabel.setText(readLabel.getText());
}
System.out.println("catchIt has released token");
}
}
}
//suspends execution when user leaves page
public void stop()
{
if (readIt != null)
{
readIt = null;
}
if (catchIt != null)
{
catchIt = null;
}
}
// act when text entered into readField
public void actionPerformed(ActionEvent e)
{
// if get here, something was entered into readField;
// set startReadIt to true so it readIt thread
// will do something
startReadIt = true;
System.out.println("something was entered into readField:");
System.out.println(readField.getText());
}
}