gpt4 book ai didi

java - 生产者 - Java 中的消费者多线程

转载 作者:搜寻专家 更新时间:2023-11-01 01:53:30 26 4
gpt4 key购买 nike

我想在 Java 中使用多线程等待和通知方法编写程序。
该程序有一个堆栈(最大长度 = 5)。生产者永远生成一个数入栈,消费者从栈中取出。

当堆栈已满时,生产者必须等待,当堆栈为空时,消费者必须等待。
问题是它只运行一次,我的意思是一旦它产生 5 个数字它就会停止但我将运行方法放在 while(true) block 中以不间断运行但它不会。
这是我到目前为止尝试过的方法。
生产者类:

package trail;
import java.util.Random;
import java.util.Stack;

public class Thread1 implements Runnable {
int result;
Random rand = new Random();
Stack<Integer> A = new Stack<>();

public Thread1(Stack<Integer> A) {
this.A = A;
}

public synchronized void produce()
{
while (A.size() >= 5) {
System.out.println("List is Full");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
result = rand.nextInt(10);

System.out.println(result + " produced ");
A.push(result);
System.out.println(A);

this.notify();
}

@Override
public void run() {
System.out.println("Producer get started");

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
produce();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

消费者:

package trail;

import java.util.Stack;

public class Thread2 implements Runnable {
Stack<Integer> A = new Stack<>();

public Thread2(Stack<Integer> A) {
this.A = A;
}

public synchronized void consume() {
while (A.isEmpty()) {
System.err.println("List is empty" + A + A.size());
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println(A.pop() + " Consumed " + A);
this.notify();
}

@Override
public void run() {
System.out.println("New consumer get started");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
consume();
}
}
}

这里是主要方法:

public static void main(String[] args) {

Stack<Integer> stack = new Stack<>();

Thread1 thread1 = new Thread1(stack);// p
Thread2 thread2 = new Thread2(stack);// c
Thread A = new Thread(thread1);
Thread B = new Thread(thread2);
Thread C = new Thread(thread2);
A.start();

B.start();
C.start();
}

最佳答案

我认为,如果您尝试将当前混合的三样东西分开,那么一般情况下理解和处理同步会更好:

  1. 将执行实际工作的任务。类 Thread1Thread2 的名称具有误导性。它们不是 Thread 对象,但它们实际上是实现您提供给 Thread 对象的 Runnable 接口(interface)的作业或任务。

  2. 您在 main 中创建的线程对象本身

  3. 在队列、堆栈等上封装同步操作/逻辑的共享对象。该对象将在任务之间共享。在这个共享对象中,您将负责添加/删除操作(使用同步块(synchronized block)或同步方法)。目前(正如已经指出的那样),同步是在任务本身上完成的(即每个任务等待并通知自己的锁,并且什么也没有发生)。当您分离关注点时,即让一个类正确地做一件事,它最终会清楚问题出在哪里。

关于java - 生产者 - Java 中的消费者多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205407/

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