public class ThreadTest
{
public static Integer i = new Integer(0);
public static void main(String[] args) throws InterruptedException
{
ThreadTest threadTest = new ThreadTest();
Runnable odd = threadTest.new Numbers(1, "thread1");
Runnable even = threadTest.new Numbers(0, "thread2");
((Thread) odd).start();
((Thread) even).start();
}
class Numbers extends Thread
{
int reminder;
String threadName;
Numbers(int reminder, String threadName)
{
this.reminder = reminder;
this.threadName = threadName;
}
@Override
public void run()
{
while (i < 20)
{
synchronized (i)
{
if (i % 2 == reminder)
{
System.out.println(threadName + " : " + i);
i++;
i.notify();
}
else
{
try
{
i.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
最佳答案
您无法在 i
上进行同步,因为它会在您的程序执行期间发生变化。
由于 Integer
在 Java 中是不可变的,在执行 i++
之后 i
将包含对另一个对象的引用,而不是你拥有的对象 同步
上。所以,你不能在这个新对象上调用wait()
/notify()
,因为这些方法可能只在你同步<的对象上调用
上,否则你会得到 IllegalMonitorStateException
。
您需要在执行期间不会更改的其他一些对象上进行同步。例如,您可以为此目的创建一个单独的对象:
public class ThreadTest {
public static Integer i = new Integer(0);
public static Object lock = new Object();
...
class Numbers extends Thread {
...
@Override
public void run() {
...
synchronized (lock) {
...
lock.notify();
...
lock.wait();
...
}
}
}
}
关于java - IlleagalMonitorStateException 当我试图运行这个程序时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953801/