リスト 6. Using specific notification with notify()
import java.util.*; //1
class Robot extends Thread
{
private RobotController controller;
private int robotID;
private byte[] lock; //2
public Robot(RobotController cntrl, int id)
{
controller = cntrl;
robotID = id;
}
public byte[] getLock() //3
{ //4
return lock; //5
} //6
public void run()
{
lock = new byte[0]; //7
synchronized(lock) //8
{
byte[] data;
while ((data = controller.getData()) == null)
{
try {
System.out.println("Thread " + robotID + " waiting");
lock.wait(); //9
}
catch (InterruptedException ie) {}
}
//Now we have data to move the robot
System.out.println("Robot " + robotID + " Working");
}
}
}
class RobotController
{
private byte[] robotData;
private Vector threadList = new Vector(); //10
private Robot rbot1;
private Robot rbot2;
private Robot rbot3;
private Robot rbot4;
private Robot rbot5;
public static void main(String args[])
{
RobotController controller = new RobotController();
controller.setup();
}
public void setup()
{
rbot1 = new Robot(this, 1);
rbot2 = new Robot(this, 2);
rbot3 = new Robot(this, 3);
rbot4 = new Robot(this, 4);
rbot5 = new Robot(this, 5);
threadList.addElement(rbot1); //11
threadList.addElement(rbot2); //12
threadList.addElement(rbot3); //13
threadList.addElement(rbot4); //14
threadList.addElement(rbot5); //15
rbot3.setPriority(Thread.MAX_PRIORITY);
rbot1.start();
rbot2.start();
rbot3.start();
rbot4.start();
rbot5.start();
begin();
}
public void begin()
{
for (int i=4;i>=0;i--) //16
{
try {
Thread.sleep(500);
}
catch (InterruptedException ie){}
putData(new byte[10]);
Robot rbot = (Robot)threadList.elementAt(i); //17
byte[] robotLock = rbot.getLock(); //18
synchronized(robotLock) { //19
System.out.println("Calling notify");
robotLock.notify(); //20
}
}
}
public synchronized byte[] getData() //21
{
if (robotData != null)
{
byte[] d = new byte[robotData.length];
System.arraycopy(robotData, 0, d, 0, robotData.length);
robotData = null;
return d;
}
return null;
}
public void putData(byte[] d)
{
robotData = d;
}
} |