gpt4 book ai didi

java - 此生产者消费者的非法监视器状态异常?

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

<分区>

正在尝试使用 Java 中的简单计数器练习生产者和消费者。不确定为什么我会在这段代码上收到非法监视器状态异常。

我有在自己的线程中运行的计数器休息和计数器消耗方法。计数器本身是一个 static int volatile 字段。计数器类也给你一个锁

如果我将 wait naotify 更改为以下内容:

Counter.lock.notify();
Counter.lock.wait();

代码有效。 wait() 和 notify() 不会自动获取同步锁的引用吗?

生产者类

package multithreading;


public class CounterProducer implements Runnable {


public void run() {

try { incrCounter(); } catch (InterruptedException e) { e.printStackTrace(); }
}

public void incrCounter() throws InterruptedException {


while (true) {
synchronized (Counter.lock) {
if (Counter.counter < 1) {
System.out.println("Counter Reset");
Counter.counter = 10;
notify();
wait();
}


}
}


}

消费类

package multithreading;


public class CounterConsumer implements Runnable {


public void run() {

try { consumeCounter(); } catch (InterruptedException e) { e.printStackTrace(); }
}

public void consumeCounter() throws InterruptedException {


while (true) {
synchronized (Counter.lock) {
if (Counter.counter > 0) {
System.out.println("Consumed");
Counter.counter--;
notify();
wait();
}


}
}


}

}

The Counter

public class Counter {

public static volatile int counter;

public static final Object lock = new Object();

}

柜台

public class CounterRunner {

public static void main(String[] args) {

Thread con = new Thread(new CounterConsumer());
Thread prod = new Thread(new CounterProducer());

con.start();
prod.start();

}


}

运行者

public class CounterRunner {

public static void main(String[] args) {

Thread con = new Thread(new CounterConsumer());
Thread prod = new Thread(new CounterProducer());

con.start();
prod.start();

}


}

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