BlockingQueue 可以安全地与多个生产者和多个使用者一起使用
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
while (true) {
queue.put(produce());
Thread.currentThread().sleep(500);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
Object produce() {
System.out.println("produce---" + Thread.currentThread().getName());
return "produce";
}
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
while (true) {
consume(queue.take());
Thread.currentThread().sleep(10000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
void consume(Object x) {
System.out.println("consume+++" + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) {
BlockingQueue q = new ArrayBlockingQueue<>(20);
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
本文介绍如何使用 Java 的 BlockingQueue 实现生产者消费者模式。通过创建生产者和消费者的线程,演示了如何安全地实现多生产者多消费者的并发场景。
1102

被折叠的 条评论
为什么被折叠?



