zoukankan      html  css  js  c++  java
  • 生产者消费者模型

    生产者

    package com.java.se.producer;
    
    import java.util.concurrent.BlockingQueue;
    
    public class Producer implements Runnable{
        
        
        private BlockingQueue<Integer>  queue;
    
        @Override
        public void run() {
            produce();
        }
        
        public Producer(BlockingQueue<Integer> q) {
            this.queue = q;
        }
        private void produce() {
            
            for (int i = 0; i<100;i++) {
                this.queue.offer(i);
            }
        }
    
    }

    消费者

    package com.java.se.producer;
    
    public class ConsumerTask implements Runnable {
    
        Integer a;
    
        public ConsumerTask(Integer a) {
            this.a = a;
        }
    
        @Override
        public void run() {
            System.out.println("消费了" + a);
        }
    
    }

    main程序

    package com.java.se.producer;
    
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class ProducerConsumerThread {
    
        private ThreadPoolExecutor threadPoolExecutor;
        private BlockingQueue<Integer> queeue;
    
        public ProducerConsumerThread() {
            int corePoolSize = Runtime.getRuntime().availableProcessors()*2;
            long keepAliveTime = 1000;
            this.threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, corePoolSize + 1, keepAliveTime,
                    TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100));
            this.queeue = new LinkedBlockingQueue<>();
        }
    
        public void consumer() {
            while (true) {
                Integer i;
                try {
                    i = this.queeue.poll(2, TimeUnit.SECONDS);
                    if (i == null) {
                        break; // 跳出循环
                    }
                    threadPoolExecutor.submit(new ConsumerTask(i));
    //new ConsumerTask(i).run(); }
    catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void start() { long start = System.currentTimeMillis(); new Producer(queeue).run(); consumer(); long end = System.currentTimeMillis(); System.out.println("coast " + (end - start) / 1000); } public static void main(String[] args) { ProducerConsumerThread t = new ProducerConsumerThread(); t.start(); } }

    注意的是 如果使用线程池消费,那么无法保证有序消费。如果要求有序消费使用注释代码

  • 相关阅读:
    免费的视频、音频转文本
    Errors are values
    Codebase Refactoring (with help from Go)
    Golang中的坑二
    Cleaner, more elegant, and wrong(msdn blog)
    Cleaner, more elegant, and wrong(翻译)
    Cleaner, more elegant, and harder to recognize(翻译)
    vue控制父子组件渲染顺序
    computed 和 watch 组合使用,监听数据全局数据状态
    webstorm破解方法
  • 原文地址:https://www.cnblogs.com/chenyangwang/p/12014204.html
Copyright © 2011-2022 走看看