I don't completely understand how wait
and notify
(of Object
) work, and as a result I'm forced to slim down my attempts into the following section of code.
Main.java:
import java.util.ArrayList;
class Main
{
public static Main main = null;
public static int numRunners = 4;
public static ArrayList<Runner> runners = null;
public static void main(String[] args)
{
main = new Main();
}
Main()
{
runners = new ArrayList<Runner>(numRunners);
for (int i = 0; i < numRunners; i++)
{
Runner r = new Runner();
runners.add(r);
new Thread(r).start();
}
System.out.println("Runners ready.");
notifyAll();
}
}
Runner.java:
class Runner implements Runnable
{
public void run()
{
try
{
Main.main.wait();
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}
Currently I get an IllegalMonitorStateException when calling Main.main.wait();
, but I don't understand why. From what I can see, I need to synchronize Runner.run
, but in doing so I assume it would only notify one thread, when the idea is to notify them all.
I've looked at java.util.concurrent
, but I can't find a suitable replacement (maybe I'm just missing something).
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…