gpt4 book ai didi

java - 生产者线程之后的最终消费者线程并消耗所有元素

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

我已经编写了使用等待和通知来实现生产者消费者问题的代码。它工作正常但问题是消费者线程在无限循环中运行并且即使在生产者线程完成并且消费者已经消耗了列表中的所有元素之后仍在等待。

public class Practice {

public static void main(String[] args) {

List<Employee> empList = new ArrayList<Employee>();
Thread producer = new Thread(new Producer(empList , 2) , "Producer");
Thread consumer = new Thread(new Consumer(empList , 2) , "Consumer");

producer.start();
consumer.start();
}

}

class Employee
{
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
class Producer implements Runnable
{
List<Employee> empList;
int size;

public Producer(final List<Employee> empList , final int size)
{
this.empList = empList;
this.size = size;
}

@Override
public void run()
{
for(int i=0; i<5;i++)
{
try {
produce(new Employee());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void produce(Employee e) throws InterruptedException
{
synchronized(empList){
while(empList.size()==size) // If list is full then will have to wait
{

System.out.println("List is full "+Thread.currentThread().getName()+" Is waiting and" + " Size is "+empList.size());
empList.wait();
}
}

synchronized(empList)
{
System.out.println("Producing");
empList.add(e);
empList.notifyAll();
}
}
}


class Consumer implements Runnable
{
List<Employee> empList;
int size;

public Consumer(final List<Employee> empList , final int size)
{
this.empList = empList;
this.size = size;
}

@Override
public void run()
{
while(true)
{
try {
System.out.println("Consumed ");
consume();
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void consume() throws InterruptedException
{
synchronized(empList){
while(empList.isEmpty()) // If list is empty then will have to wait
{
System.out.println("List is empty "+Thread.currentThread().getName()+" Is waiting and " + "Size is "+empList.size());
empList.wait();
}
}

synchronized(empList)
{
empList.notifyAll();
empList.remove(0);
}

}

}

请告诉我如何在生产者完成并且消费者已经消耗了列表中的所有元素后停止我的消费者线程。请帮助我的代码。提前致谢

最佳答案

只需添加标志,在生产者和消费者之间共享:

static bool producerFinished = false;

在它生产完所有元素后在生产者中设置它:

public void run()
{
// ...
synchronized(empList){
producerFinished = true;
empList.notifyAll();
}
}

并在消费者的 while() 循环中检查它以及列表是否为空

public void consume()
{
synchronized(empList){
while(empList.isEmpty() && !producerFinished)
{
empList.wait();
}

if(!empList.isEmpty())
{
//consume element
}
else
{
//List is empty and producer has finished.
}
}
}

关于java - 生产者线程之后的最终消费者线程并消耗所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091328/

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