java生产者消费者模式
package com.thread; import java.util.ArrayList;import java.util.List; public class ProCon {public static void main(String[] args) {Queue queue=new Queue(10);new Thread(new Productor(queue)).start();new Thread(new Productor(queue)).start();new Thread(new Productor(queue)).start();new Thread(new Consumer(queue)).start();}public static class Queue{List list=new ArrayList();int size=0;public Queue(int size){this.size=size;}public synchronized String get(){if(list.size()==0){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}else{this.notify();String ele=list.remove(0);System.out.println(list.size()+":get:"+ele);return ele;}return null;}public synchronized void put(){if(list.size()>=size){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}else{this.notify();String ele=Math.random()+"";list.add(ele);System.out.println(list.size()+":put:"+ele);}}}public static class Productor implements Runnable{Queue queue;public Productor(Queue queue){this.queue=queue;}@Overridepublic synchronized void run() {while(true){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}queue.put();}}}public static class Consumer implements Runnable{Queue queue;public Consumer(Queue queue){this.queue=queue;} @Overridepublic void run() {while(true){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}queue.get();}} }}
?