java - 同步块锁定在类
问题描述
在下面的生产者和消费者代码中,我认为生产()和消费()方法在类锁(Processor.class)上是同步的,但是我收到一个异常说明 IllegalMonitorStateException,它发生在我们不使用的对象上t 获取锁,但我们通知该对象。
谁能告诉我我在程序中哪里出错了。
package ProducerConsumer;
public class Main {
public static void main(String[] args) {
Processor processor = new Processor();
Thread producer = new Thread(new Runnable() {
public void run() {
try {
processor.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(new Runnable() {
public void run() {
try {
processor.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("\t\t\tStarting both producer and consumer Threads.");
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\t\t\tEnding all the Threads.");
}
}
import java.util.List;
import java.util.ArrayList;
public class Processor {
private List<Integer> list = new ArrayList<>();
private int value = 0;
private final int LIMIT = 5;
public void produce() throws InterruptedException
{
synchronized(Processor.class){
while(true)
{
if(list.size() == LIMIT){
System.out.println("Waiting for consumer to consume resources");
wait();
}
else{
value++;
System.out.println("The produced resource is : "+value);
list.add(value);
notify();
}
}
}
}
public void consume() throws InterruptedException
{
synchronized(Processor.class){
while(true)
{
if(list.isEmpty()){
System.out.println("Waiting for producer to produce the resources");
wait();
}
else{
System.out.println("The consumer Consumed Resource is : "+list.remove(0));
notify();
}
}
}
}
}
解决方案
您的wait()
&在ienotify()
上被调用,但您正在对象上锁定/同步。您可以修复您的代码以如下方式工作。this
Processor processor = new Processor();
Processor.class
class Processor {
private List<Integer> list = new ArrayList<>();
private int value = 0;
private final int LIMIT = 5;
public void produce() throws InterruptedException
{
synchronized(Processor.class){
while(true)
{
if(list.size() == LIMIT){
System.out.println("Waiting for consumer to consume resources");
Processor.class.wait();
}
else{
value++;
System.out.println("The produced resource is : "+value);
list.add(value);
Processor.class.notify();
}
}
}
}
public void consume() throws InterruptedException
{
synchronized(Processor.class){
while(true)
{
if(list.isEmpty()){
System.out.println("Waiting for producer to produce the resources");
Processor.class.wait();
}
else{
System.out.println("The consumer Consumed Resource is : "+list.remove(0));
Processor.class.notifyAll();
}
}
}
}
}
推荐阅读
- java - Instagram如何将评论textview和用户名textview合二为一?
- docker - kubernetes prestop 钩子不适用于环境变量
- python - rpsls 游戏“(python)错误:无法连接'str'和'int'对象
- here-api - 我应该选择什么 HEREMaps 计划才能执行反向地理编码批处理请求?
- c++ - 有符号-无符号加法行为异常
- birt - 如何在 birt 报告中添加依赖于名称的图像?
- python - 通过句柄在画布中查找小部件
- maven - Maven:如何在构建和发布期间跳过安装/部署快速入门或示例模块?
- javascript - Vuejs fusioncharts 具有完全透明的背景
- angularjs - 为什么 $invalid、$valid、$dirty 在 Visual Studio 的 AngularJS 项目中不起作用?