gpt4 book ai didi

java - 为什么会出现 IllegalMonitorStateException?

转载 作者:太空宇宙 更新时间:2023-11-04 11:34:31 25 4
gpt4 key购买 nike

我正在尝试使用三个线程交替打印。第一个线程应该打印一个数字,然后第二个线程打印第二个数字,然后第三个线程。我尝试使用共享静态整数来实现它,但我的代码显示 IllegalMonitorStateException。任何人都可以检查一下并告诉我的错误吗?

class ThreadRevisit extends Thread
{
static Integer number;
int num;
ThreadRevisit(String name,Integer number,int num)
{
super(name);
this.number=number;
this.num=num;
}

public void run()
{
int n= number;
do
{
synchronized(ThreadRevisit.number)
{
if(n>100)
{
number.notifyAll();
break;
}
if (n%3==num)
{
System.out.println(Thread.currentThread().getName()+" "+num);
number=number+1;
}
number.notifyAll();
try
{
number.wait();
}catch(Exception e)
{

}
}
}
while(true);

}
}
class T1
{
public static void main(String[] ar)
{
Integer inn=new Integer(0);
ThreadRevisit.number=inn;
ThreadRevisit t1=new ThreadRevisit("one",inn,0);
ThreadRevisit t2=new ThreadRevisit("two",inn,1);
ThreadRevisit t3=new ThreadRevisit("three",inn,2);

t1.start();
t2.start();
t3.start();
}

最佳答案

第 27 行

number=number+1;

您可以有效地将对象编号更改为具有更高值的新对象编号。所以新的没有连接显示器,这会导致错误。

关于java - 为什么会出现 IllegalMonitorStateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com