您的位置:首页 > 编程语言 > Java开发

【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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程