gpt4 book ai didi

java - 队列中的非法监视器

转载 作者:行者123 更新时间:2023-12-01 17:29:02 26 4
gpt4 key购买 nike

我有以下代码来启动 3 个在队列对象上同步的线程(在构造时传递)。每个线程尝试从队列中读取数据来执行操作:

class smokers extends Thread{

final Queue q;
boolean smoked=false;

public smokers(Queue q,restype res){
this.q=q;
....
}

public void run(){

try{
while(smoked==false){
synchronized(q){
if (q.size()==0) wait();
...
q.poll();
notify();
}
}
}
}catch (InterruptedException intEx)
{
intEx.printStackTrace();
}

}

public static void main(String[] args){
final Queue q=new LinkedList();
....
while (q.size()<10){
q.add(....);
}
smokers[] smokers=new smokers[3];
smokers[0]=new smokers(q,restype.TOBACCO);
smokers[1]=new smokers(q,restype.PAPER);
smokers[2]=new smokers(q,restype.MATCH);

// Start the smokers
for (int i = 0; i < 3; i++) {
smokers[i].start();
}


// Wait for them to finish
for (int i = 0; i < 3; i++) {
try {
smokers[i].join();
} catch(InterruptedException ex) { }
}

// All done
System.out.println("Done");
}

}

我得到以下信息:

Exception in thread "Thread-2" Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.bac.threads.smokers.run(smokers.java:35)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.bac.threads.smokers.run(smokers.java:35)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.bac.threads.smokers.run(smokers.java:35)

我做错了什么?

最佳答案

您对 this 调用 notify,但在字段 q 上进行同步。wait 调用也是如此。

关于java - 队列中的非法监视器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12816684/

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