gpt4 book ai didi

java - 在 Java 中使用 wait() 和 notify() 的生产者消费者程序

转载 作者:行者123 更新时间:2023-11-29 05:13:06 25 4
gpt4 key购买 nike

我正在使用低级同步以及 wait() 和 notify() 在 Java 中解决经典的生产者-消费者问题。我知道使用 java.util.concurrent 包中的结构有更好的实现,但我的问题围绕低级实现:

private static ArrayList<Integer> list = new ArrayList<Integer>();

static Object obj = new Object();

public static void producer() throws InterruptedException {
synchronized (obj) {
while (true) {
if (list.size() == 10) {
System.out.println("Queue full.. Waiting to Add");
obj.wait();
} else {
int value = new Random().nextInt(100);
if (value <= 10) {
Thread.sleep(200);
System.out.println("The element added was : " + value);
list.add(value);
obj.notify();
}
}
}
}

}

public static void consumer() throws InterruptedException {
synchronized (obj) {
while (true) {
Thread.sleep(500);
if (list.size() == 0) {
System.out.println("Queue is empty...Waiting to remove");
obj.wait();
} else {
System.out.println("The element removed was : "
+ list.remove(0));
obj.notify();
}
}
}

}

程序中有2个线程,生产者和消费者各1个。代码工作得很好。

唯一的问题 是生产者继续生产消息直到一次达到最大值(直到列表的大小为 10),而消费者一次消费所有 10 个。

如何让生产者和消费者同时工作?

这是示例输出:

The element added was : 4
The element added was : 0
The element added was : 0
The element added was : 4
The element added was : 3
The element added was : 1
The element added was : 10
The element added was : 10
The element added was : 3
The element added was : 9
Queue full.. Waiting to Add
The element removed was : 4
The element removed was : 0
The element removed was : 0
The element removed was : 4
The element removed was : 3
The element removed was : 1
The element removed was : 10
The element removed was : 10
The element removed was : 3
The element removed was : 9
Queue is empty...Waiting to remove

编辑:这是更正后的代码:

private static ArrayList<Integer> list = new ArrayList<Integer>();
private static Object obj = new Object();

public static void producer() throws InterruptedException {
while (true) {
Thread.sleep(500);
if (list.size() == 10) {
System.out.println("Waiting to add");
synchronized (obj) {
obj.wait();
}
}
synchronized (obj) {
int value = new Random().nextInt(10);
list.add(value);
System.out.println("Added to list: " + value);
obj.notify();
}
}
}

public static void consumer() throws InterruptedException {
while (true) {
Thread.sleep(500);
if (list.size() == 0) {
System.out.println("Waiting to remove");
synchronized (obj) {
obj.wait();
}
}
synchronized (obj) {
int removed = list.remove(0);
System.out.println("Removed from list: " + removed);
obj.notify();
}
}
}

最佳答案

您不能在具有相同对象的同步块(synchronized block)中运行两个线程。当一个方法正在运行时,另一个方法无法运行,直到另一个线程调用wait方法。

要解决这个问题,您应该将 addremove 放在 synchronized block 中。有关详细信息,请参阅 this .

关于java - 在 Java 中使用 wait() 和 notify() 的生产者消费者程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591043/

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