gpt4 book ai didi

生产者消费者的Java实现抛出java.lang.IllegalMonitorStateException

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:54:57 25 4
gpt4 key购买 nike

import java.util.LinkedList;
import java.util.Queue;

class Producer extends PubSub implements Runnable{

@Override
public void run() {
synchronized(queue){
if (queue.size() == 99){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(2);
try{
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
notify();
}
}
}


class Consumer extends PubSub implements Runnable{

@Override
public void run() {
synchronized(queue){
if(queue.isEmpty()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(queue.poll());
}

}

}
public class PubSub {
static Integer QUEUE_SIZE = 100;
Queue<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) {
Producer producer = new Producer();
Consumer consumer = new Consumer();
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
System.out.println("Started both the threads");
}

}

我在 wait() 部分得到一个 java.lang.IllegalMonitorStateException。我想知道我在这里做错了什么。有什么想法吗??

我得到的完整异常如下。

Exception in thread "Thread-1" Started both the threads
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at Consumer.run(PubSub.java:36)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Producer.run(PubSub.java:23)
at java.lang.Thread.run(Thread.java:745)

最佳答案

您正在调用 wait() ,相当于 this.wait() , 但你没有拿着 this 的监视器.你在 queue 上拿着显示器.所以应该是queue.wait() . (与 notify() 相同)。

关于生产者消费者的Java实现抛出java.lang.IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36856753/

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