我有两个生产者和一个消费者:
public class Main {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<Integer> integersQueue = new ArrayBlockingQueue<>(20);
final Thread producer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
integersQueue.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final Thread thread = new Thread(() -> {
while (integersQueue.size() > 0) { //Wait while all producers work
try {
System.out.println("GET: " + integersQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread1 = new Thread(producer);
Thread thread2 = new Thread(producer);
thread1.start();
thread2.start();
Thread.sleep(5000);
thread.start();
}
}
如果所有生产者都完成了,我正试图找到一种方法来阻止消费者。有多个生产者,但只有一个消费者。我需要一些毒丸,但如何从不同的生产商指定它?我发现了这个:https : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html但我不明白如何应用它?
饮歌长啸
胡说叔叔
相关分类