gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:57:33 26 4
gpt4 key购买 nike

我正在做一些有关多线程和 Java 并发功能的练习。我有 1 个生产者和 4 个消费者。现在我的问题是:当我确定生产者已经完成 BlockingQueue 中的生产时,是否有其他更聪明的方法来阻止消费者?现在我在队列中使用 -1 整数,但看起来非常基本!谢谢

public class Exercise {

static class Producer implements Runnable {
int counter=0;
private BlockingQueue<Integer> queue;
Producer(BlockingQueue<Integer> q) {
queue = q;
}
public void run() {
try {
while (counter<100000000) {
queue.put(produce());
}
queue.put(new Integer(-1));
queue.put(new Integer(-1));
queue.put(new Integer(-1));
queue.put(new Integer(-1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Integer produce() {
counter++;
return new Integer(counter);

}
}

static class Consumer implements Runnable {
private final BlockingQueue<Integer> queue;
private String name;
private long sum;

Consumer(BlockingQueue<Integer> q, String name) {
queue = q;
this.name=name;
sum=0;
}

public void run() {
try {
int x=0;
while (x>=0) {
x=queue.take();
if(x!=-1)sum+=x;
}
System.out.println(sum+" of "+ name);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}



public static void main(String[] args) {

ExecutorService exec = Executors.newFixedThreadPool(6);
BlockingQueue<Integer> q =new LinkedTransferQueue<Integer>();
Producer p=new Producer(q);
Consumer c1 = new Consumer(q,"consumer1");
Consumer c2 = new Consumer(q,"consumer2");
Consumer c3 = new Consumer(q,"consumer3");
Consumer c4 = new Consumer(q,"consumer4");
exec.submit(p);
exec.submit(c1);
exec.execute(c2);
exec.submit(c3);
exec.execute(c4);
exec.shutdown();
}

}

最佳答案

您可以使用毒丸,但是使用这种毒丸的更有效方法是不将其从队列中删除(或者如果您这样做,则将其放回去)这种方式对于生产者来说不需要知道如何您拥有许多消费者。

顺便说一句,我会避免使用显式装箱,因为它更冗长且更慢。

而不是

queue.put(new Integer(-1));

你可以写

queue.put(-1);

甚至更好

static final int POISON_PILL = -1;

// on the producer
queue.put(POISON_PILL);

// on the consumer
while ((x = queue.take()) != POISON_PILL) {
sum += x;
queue.put(POISON_PILL);

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

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