• 生产者消费者【其他模式】


    生产者消费者【其他模式】

    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);
            }
        }
    }
    
  • 相关阅读:
    WordPress使用记录
    Sql Server数据库的存储过程
    (一)vs2010 新建、使用dll
    Commons Betwixt : Turning beans into XML
    error: failed to attach to process ID 0
    java中常用的内存区域
    计算N阶乘中结尾有多少零
    计算出两个日期相隔多少天
    Cognos Active Report 时间区间选择的解决办法
    PHP heredoc 用法
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10211236.html
Copyright © 2020-2023  润新知