练习题之生产者消费者模型
生产者、消费者模型
方式一:以LinkedBlockingQueue阻塞队列的方式来进行存储
public class Producer implements Runnable { //共享队列 private BlockingQueue blockingQueue ; private final int MAX_NUM=10; public Producer(BlockingQueue blockingQueue) { this.blockingQueue = blockingQueue; } public void run() { for(int i=0;i<MAX_NUM;i++){ blockingQueue.put(i); } } } public class Consumer implements Runnable { private BlockingQueue blockingQueue; public Consumer(BlockingQueue blockingQueue) { this.blockingQueue = blockingQueue; } public void run() { while(true) { blockingQueue.take(); } } } public class ProducerConsummer { public static void main(String [] args) { BlockingQueue blockingQueue = new LinkedBlockingQueue(); Producer producer = new Producer(); new Thread(producer).start(); Cosummer cosummer = new Consummer(); new Thread(cosummer).start(); } }
方式二:以ArrayBlockingQueue有界阻塞队列的方式来存储
public class TestMain { public static void main(String [] args) { ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10); //生产者 for(int i=0;i<10;i++) { int temp = i; new Thread(new Runnable() { public void run() { synchronized(TestMain.class) { queue.put(temp); System.out.println(Thread.currentThread().getName() + " put [" + temp +"]"); } } },"Thead-"+i).start(); } //消费者 new Thread(new Runnable() { public void run() { while(true) { Integer i = queue.take(); System.out.println(Thread.currentThread().getName() + "get [" + i + "]"); Thread.sleep(1000); } } },"Cosummer").start(); } }
方式三:以wait/notify方式进行处理
public class Producer implements Runnable { private List<Object> storeHouse = new LinkedList<Object>(); private final int MAX_NUM=10; public Producer(List<Object> storeHouse) { this.storeHouse = storeHouse; } public void product(){ synchroized(storeHouse) while(storeHouse.size()==MAX_NUM) { System.out.println("The storeHouse is full,please wait"); storeHouse.wait(); } Object newOb = new Object(); if(storeHouse.add(newOb) { System.out.println("Producer put a Object to the storeHouse "); storeHouse.notify(); } } public void run() { while(true) { product(); } } } public class Consummer implements Runnable { private List<Object> storeHouse = new LinkedList<Object>(); public Consummer(List<Object> storeHouse) { this.storeHouse = storeHouse; } public void comsummer() { synchroized(storeHouse) { while(storeHouse.size==0) { System.out.println("The storeHouse is empty,please wait"); storeHouse.wait(); } storeHouse.removeLast(); System.out.println("Cosummer a Object from the storeHouse "); storeHouse.notify(); } } public void run() { while(true) { comsummer(); } } } public class ProducerConsummer { public static void main(String [] args) { List<Object> storeHouse = new LinkedList<Object>(); Producer producer = new Producer(storeHouse); new Thread(producer).start(); Consummer comsummer = new Consummer(storeHouse); new Thread(comsummer).start(); } }
关于生产者、消费者模型可以参考:http://blog.csdn.net/monkey_d_meng/article/details/6251879