生產者消費者【其他模式】
阿新 • • 發佈:2019-01-02
生產者消費者【其他模式】
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); } } }