码迷,mamicode.com
首页 > 其他好文 > 详细

生产者消费者模型

时间:2019-12-10 00:35:54      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:exe   exec   keep   无法   import   mil   sub   proc   integer   

生产者

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

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

 

 

生产者消费者模型

标签:exe   exec   keep   无法   import   mil   sub   proc   integer   

原文地址:https://www.cnblogs.com/chenyangwang/p/12014204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!