生产者消费者模型
生产者
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(); } }
注意的是 如果使用线程池消费,那么无法保证有序消费。如果要求有序消费使用注释代码