【java多线程之】生产者消费者示例
2014-10-26 21:29
288 查看
<span style="font-family: Arial, Helvetica, sans-serif;">package com.oterman.traditional;</span></span>
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * 该例子演示了生产者和消费者: * 两个线程,一个充当生产者,一个充当消费者,还有一个用来表示产品的类。 * 要求:生产一个产品,消费一个产品,一个产品不可以被多次消费;生产产品和消费产品都需要时间。 * */ public class ConsumerProducerDemo { public static void main(String[] args) { Goods goods=new Goods(0); Consumer consumer=new Consumer(goods); Producer producer=new Producer(goods); new Thread(producer).start(); new Thread(consumer).start(); } } //模拟生产者和消费的操作的商品 class Goods { private int id; boolean isShouldPro=true; private BlockingQueue<String> queue=new ArrayBlockingQueue<String>(1); public Goods(int id){ this.id=id; } public synchronized void produce(){ while(!isShouldPro){//判断是否该生产者生产;如果不该,则进入等待状态; try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000);//模拟生产时间; System.out.println(Thread.currentThread().getName()+"生产了一个商品,id="+(++id)); } catch (Exception e) { e.printStackTrace(); } isShouldPro=false;//改变标记,让消费者线程开始执行; this.notifyAll();//通知在此监视器等待的所有线程; } public synchronized void consume(){ while(isShouldPro){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"消费了一个产品,id="+id); isShouldPro=true; this.notifyAll(); } } class Producer implements Runnable{ private Goods goods=null; public Producer(Goods goods){ this.goods=goods; } public void run(){ while(true){ goods.produce(); } } } class Consumer implements Runnable{ private Goods goods=null; public Consumer(Goods goods){ this.goods=goods; } public void run(){ while (true) { goods.consume(); } } } </span>
相关文章推荐
- 22.用JAVA中的多线程示例生产者和消费者问题
- 用JAVA中的多线程示例生产者和消费者问题
- Java基础多线程间通讯之多生产者、多消费者模式示例:
- 用JAVA中的多线程示例生产者和消费者问题
- Java 多线程生产者和消费者代码示例
- 由生产者/消费者问题看JAVA多线程
- JAVA多线程实例(生产者与消费者问题)
- java 多线程 生产者消费者
- java多线程总结六:经典生产者消费者问题实现
- 由生产者/消费者问题看JAVA多线程
- java多线程 消费者-生产者
- JAVA [ 多线程 -- 生产者消费者 ]
- 回顾生产者/消费者问题下产生的java多线程(二)
- 由生产者/消费者问题看JAVA多线程
- java多线程 生产者 消费者 问题 。。。
- java 多线程之 wait(),notify(),notifyAll()以及经典的生产者消费者模型
- JAVA多线程模拟生产者与消费者_实例
- java多线程 消费者-生产者
- java多线程 生产者 消费者 问题 。。。
- JAVA多线程-生产者与消费者当线程多时发生死锁的解决方法