首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java生产者消费者形式

2012-10-25 
java生产者消费者模式package com.thread import java.util.ArrayListimport java.util.List public cl

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

?

热点排行