生产者消费者【其他模式】
public class ProducerConsumer {
/**
* Producer Consumer Pattern【生产者消费者模式】:
* 将生产者应用与消费者应用解耦,生产者和消费者能够以不同的速率进行工作。
*/
@Test
public void all() throws InterruptedException {
final ExecutorService threadPool = Executors.newFixedThreadPool(5);
final BlockingQueue<String> itemQueue = new ArrayBlockingQueue<>(1);
for (int i = 0; i < 3; i++) {
threadPool.submit(() -> new Consumer(itemQueue).run());
}
for (int i = 0; i < 2; i++) {
threadPool.submit(() -> new Producer(itemQueue).run());
}
threadPool.awaitTermination(2, TimeUnit.SECONDS);
}
}
@Slf4j
@AllArgsConstructor
class Consumer {
private final BlockingQueue<String> sharedItemQueue;
public void run() {
try {
while (!Thread.interrupted()) {
final String item = sharedItemQueue.take();
log.info("{} consume {}", Thread.currentThread().getName(), item);
}
} catch (final InterruptedException e) {
log.error("", e);
}
}
}
@Slf4j
@AllArgsConstructor
class Producer {
private final BlockingQueue<String> sharedItemQueue;
private static final AtomicInteger COUNT = new AtomicInteger();
public void run() {
try {
while (!Thread.interrupted()) {
final String item = Thread.currentThread().getName() + COUNT.incrementAndGet();
log.info("{} produce {}", Thread.currentThread().getName(), item);
sharedItemQueue.put(item);
}
} catch (final InterruptedException e) {
log.error("", e);
}
}
}