Java Wait and Notify: IllegalMonitorStateException
我不完全理解 和 (of) 是如何工作的,因此我被迫将我的尝试缩减到下面的代码部分。wait
notify
Object
主要.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();
}
}
亚军.java:
class Runner implements Runnable
{
public void run()
{
try
{
Main.main.wait();
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}
目前,我在打电话时得到了一个非法的MonitorStateException,但我不明白为什么。从我所看到的, 我需要 同步 ,但是在这样做时,我假设它只会通知一个线程,而这个想法是通知它们。Main.main.wait();
Runner.run
我已经看过了,但我找不到合适的替代品(也许我只是错过了一些东西)。java.util.concurrent