• 生产者消费者模型


    生产者

    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(); } }

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

  • 相关阅读:
    TF.VARIABLE和TENSOR的区别(转)
    同步与异步,阻塞与非阻塞的区别
    tensorflow op tf.global_variables_initializer
    iOS viewDidUnload方法
    Objective-C中的@property和@synthesize用法
    UIDatePicker的时间选择器里的时区的问题
    IOS 小技巧积累
    IOS atomic与nonatomic,assign,copy与retain的定义和区别
    XCODE4.6从零开始添加视图
    Xcode无法设置视图的 autosizing control原因
  • 原文地址:https://www.cnblogs.com/chenyangwang/p/12014204.html
Copyright © 2020-2023  润新知