gpt4 book ai didi

java - 为什么消费者中的wait()无法从生产者notifyall()获得通知?

转载 作者:行者123 更新时间:2023-12-02 05:06:22 24 4
gpt4 key购买 nike

以下是我的代码

public class Factory {

static boolean iteminfactory = false;
public synchronized void producer(int i ) throws InterruptedException {
System.out.println("Producer started " + iteminfactory);
if (iteminfactory) {
wait();
}

System.out.println("Produced " + i);
iteminfactory = true;
notifyAll();
System.out.println("Producer ended " + iteminfactory);
}

public synchronized void consumer() throws InterruptedException {
System.out.println("Consume started " + iteminfactory);
if (!iteminfactory) {
wait(); // problem , not able to get notification from producer
}

System.out.println("Consumed");
iteminfactory = false;
notifyAll();
System.out.println("Consumer ended " + iteminfactory);
}

}

// producer
package com.example.suri;

public class Producer implements Runnable{
static Factory f;

public Producer () {
f = new Factory();
}
@Override
public void run() {
for (int i = 0; i < 10 ; ++i) {
try {
f.producer(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

//consumer

public class Consumer implements Runnable {
static Factory f;

public Consumer() {
f = new Factory();
}
@Override
public void run() {

for (int i = 0; i < 10 ; ++i) {
try {
f.consumer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

// main

public static void main(String[] args) {

Producer p = new Producer();
Consumer c = new Consumer();

Thread tp = new Thread(p);
Thread tc = new Thread(c);

tp.start();
tc.start();
}

output

Producer started false
Consume started false
Produced 0
Producer ended true
Producer started true

消费者函数中的 wait 没有收到生产者的通知。为什么会这样?如果我为 Factory 创建单个实例并与消费者和生产者共享,则一切正常。即像这样改变构造函数。

Producer(Factory fact) {
f = fact;
}
Consumer (Factory fact) {
f = fact;
}

// Main
Factory f = new Factory();
Producer p = new Producer(f);
Consumer c = new Consumer(f);

但我的问题是为什么notifyall()要区分工厂实例,因为它应该只通知正在等待的线程

最佳答案

wait/notify/notifyAll api 尝试获取封闭实例上的互斥锁。因此,如果您正在等待来自 object1 的通知,那么只有 object1 可以通知,而 object2 则不能。

参见this了解详情。

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution. 

在 Factory 中,您正在同步该对象,即特定实例。在您的生产者和消费者类中,您正在实例化工厂,因此您有两个不同的实例,因此您在两个不同的实例上进行同步。

我建议,您通过构造函数注入(inject)工厂,以便生产者和消费者使用相同的工厂实例,从而在公共(public)工厂对象上同步。

关于java - 为什么消费者中的wait()无法从生产者notifyall()获得通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756564/

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