import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/*
生产者 消费者
*/
class Resource
{
private String name;
private int count=1;
private boolean flag =false;
//创建一个锁对象
java.util.concurrent.locks.Lock lock =new ReentrantLock();
//通过已有的锁获取该锁上的监视器对象
//Condition c1 =lock.newCondition();
//通过已有的锁创建生产者监视器 消费者监视器
Condition pro_c1 =lock.newCondition();
Condition consum_c1=lock.newCondition();
public void set(String name)
{
lock.lock();
try{
if(flag)
try
{
pro_c1.await();
}
catch (InterruptedException e)
{
}
this.name=name+count;
count++;
System.out.println(this.name+"...生产者5.0"+Thread.currentThread().getName());
flag =true;
consum_c1.signal();
}
finally
{
lock.unlock();
}
}
public void out()
{
lock.lock();
try{
if(!flag)
try {
consum_c1.await();
}
catch (InterruptedException e)
{
}
System.out.println(this.name+"...+.消费者8..."+Thread.currentThread().getName());
flag=false;
pro_c1.signal();
}
finally
{
lock.unlock();
}
}
}
class Producter implements Runnable
{
private Resource r;
Producter(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("烤鸭");
}
}
}
class Consum implements Runnable
{
private Resource r;
Consum(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
public class ProductionDemo
{
public static void main(String []args)
{
Resource r =new Resource();
Producter p = new Producter(r);
Consum c =new Consum (r);
Thread t =new Thread(p);
Thread t1 =new Thread(p);
Thread t2 =new Thread(c);
Thread t3 =new Thread(c);
t.start();
t1.start();
t2.start();
t3.start();
}
}