本帖最后由 treecolor166 于 2013-12-29 23:55 编辑
请问下面的代码为什么只有2个线程在打印其它线程怎么都停在那里不输出了呢
public class ProducerConsumerDemo2
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource
{
private String name;
private int count=1;
private boolean flag;
//创建锁
Lock lock=new ReentrantLock();
//通过锁对象创建2组监视器对象,分别用于监视生产者和消费者
Condition producer_con=lock.newCondition();
Condition consumer_con=lock.newCondition();
public synchronized void set(String name)
{
lock.lock();
try
{
while(flag)
try{producer_con.await();}catch(InterruptedException e){}
this.name=name+(count++);
System.out.println(Thread.currentThread().getName()+"....生产"+this.name);
flag=true;
consumer_con.signal();
}
finally
{
lock.unlock();
}
}
public synchronized void out()
{
lock.lock();
try
{
while(!flag)
try{consumer_con.await();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"*************消费"+this.name);
flag=false;
producer_con.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("商品");
}
}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
|