java的多生产者多消费者例子

import java.util.concurrent.locks.*;


public class Test9 {

public static void main(String[] args) {
// TODO 自动生成的方法存根
Resource r=new Resource();
Producer p=new Producer(r);
Consumer c=new Consumer(r);
Thread t0=new Thread(p);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
Thread t3=new Thread(c);
t0.start();
t1.start();
t2.start();
t3.start();
}

}

class Resource
{
private String name;
private int count=1;
private boolean flag;

//创建一个锁对象。
Lock lock ;
//通过已有的锁获取两组监视器对象,一组监视生产者,一组监视消费者。
Condition producer_con ;
Condition consumer_con ;
public Resource()
{
this.lock= new ReentrantLock();
this.producer_con = lock.newCondition();
this.consumer_con = lock.newCondition();
}

public void set(String name)
{
lock.lock();
try {
while(flag)
producer_con.await();
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"....生产者..."+this.name);
flag=true;
consumer_con.signal();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void get()
{
lock.lock();
try {
while(!flag)
consumer_con.await();
System.out.println(Thread.currentThread().getName()+"....消费者......."+this.name);
flag=false;
producer_con.signal();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
lock.unlock();
}

}
}
class Producer implements Runnable
{

Resource r=null;
public Producer(Resource r)
{
this.r=r;
}
public void run() {
// TODO 自动生成的方法存根
while(true)
r.set("烤鸭");
}

}

class Consumer implements Runnable
{

Resource r=null;
public Consumer(Resource r)
{
this.r=r;
}
public void run() {
// TODO 自动生成的方法存根
while(true)
r.get();
}
}

posted @ 2014-09-16 22:08  加肥猫咪  阅读(285)  评论(0编辑  收藏  举报