本帖最后由 徐军涛 于 2012-12-3 17:25 编辑
仿照老师写的,怎么么米有结果?
------------------------------------
public class ProduceConsumer {
public static void main(String[] args) {
//声明资源对象
Resource src = new Resource();
//声明生产者
Produce p = new Produce(src);
//声明消费者
Consumer c = new Consumer(src);
//声明2个生产者对象 线程
Thread pro1 = new Thread(p);
Thread pro2 = new Thread(p);
//声明2个消费者对象 线程
Thread con1 = new Thread(c);
Thread con2 = new Thread(c);
//开启线程
pro1.start();
pro2.start();
con1.start();
con2.start();
}
}
//创建资源
class Resource{
private String name;//产品的名称
private int count= 1;//产品的编号
private boolean flag ;//声明标记
//声明锁对象
private final Lock lock = new ReentrantLock();
//生产者监视器
private Condition pro_con = lock.newCondition();
//消费者监视器
private Condition con_con = lock.newCondition();
//生产产品
public void set(String name){
//获取锁
lock.lock();
try {
while(flag)
try{pro_con.await();}catch(InterruptedException e){}
this.name = name+count;
count++;
System.out.println(Thread.currentThread().getName()+"---生产者--"+this.name);
flag = true;
con_con.signal();
}
}finally{
//释放锁
lock.unlock();
}
//消费产品
public void get(){
lock.lock();
try {
while(!flag)
try{con_con.await();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"--消费者---"+this.name);
flag = false;
pro_con.signal();
}
} finally{
lock.unlock();
}
}
//创建生产者
class Produce implements Runnable{
//资源对象
private Resource r;
@Override
public void run() {
while(true){
r.set("馒头");
}
}
public Produce(Resource r) {
super();
this.r = r;
}
}
//创建消费者
class Consumer implements Runnable{
//资源对象
private Resource r;
@Override
public void run() {
while(true){
r.get();
}
}
public Consumer(Resource r) {
super();
this.r = r;
}
}
|
|