Java生产者消费者模式
2013-10-25 21:53
459 查看
package ProductConsumer; import org.ietf.jgss.Oid; public class Test { public static void main(String[] args){ Market mt=new Market(); Product product=new Product(mt); Consumer consumer=new Consumer(mt); new Thread(product).start(); new Thread(consumer).start(); } } class Product implements Runnable{ Market market=null; public Product(Market mt){ this.market=mt; } @Override public void run() { // TODO Auto-generated method stub for(int i = 0; i < 20; i++) { WoTou wt=new WoTou(i); market.push(wt); System.out.println("生产了:"+wt); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer implements Runnable{ Market market=null; public Consumer(Market mt){ this.market=mt; } @Override public void run() { // TODO Auto-generated method stub for(int i = 0; i < 60; i++) { /*WoTou wt=new WoTou(i); market.push(wt);*/ WoTou wTou=market.pop(); System.out.println("消费了:"+wTou); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Market { WoTou[] wtArr=new WoTou[6]; int index=0; public synchronized void push(WoTou wt){ wtArr[index]=wt; index++; while(index==wtArr.length) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify(); } public synchronized WoTou pop(){ while (index==0) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify(); index--; return wtArr[index]; } } class WoTou{ int id; public WoTou(int id){ this.id=id; } @Override public String toString() { // TODO Auto-generated method stub return "WOTUO:"+id; } }
相关文章推荐
- Java多线程之并发协作生产者消费者设计模式JDK1.5.0+升级优化版
- java技术深入(一)——java多线程(七)——阻塞队列,生产者-消费者模式
- Java线程间同步实现生产者-消费者模式
- JAVA 生产者消费者模式的实现
- Java线程(三):线程协作-生产者/消费者模式
- Java程序性能优化 读书笔记(十四)并行设计模式:生产者-消费者模式
- JAVA多线程-线程间通信(二)-生产者/消费者模式实现
- Java生产者-消费者模式的非阻塞队列实现
- java消费者生产者模式及JDK之阻塞队列LinkedBlockingQueue实现
- java多线程之消费者生产者模式
- JAVA 阻塞队列实现 生产者和消费者 模式
- java 编码实现简单的生产者-消费者模式
- Java_生产者消费者模式
- java多线程之消费者生产者模式
- Java多线程设计(四)生产者/消费者模式
- Java多线程-生产者消费者模式
- 基于Java阻塞队列实现生产者与消费者模式
- Java 并发编程(四)阻塞队列和生产者-消费者模式
- java多线程之消费者生产者模式
- JAVA生产者与消费者模式 BlockingQueue与ExecutorService实例