需求:用多线程解决多生产者、多消费者的问题
在同步部分,用Lock替代了synchronized,用Condition替代Objiect的监视器方法
import java.util.concurrent.locks.*; //导入包
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
Lock lock=new ReentrantLock();//用Lock创建一个锁
Condition con_con=lock.newCondition();//用这个锁创建一个消费者监视器(返回绑定到此 Lock 实例的新 Condition 实例)。
Condition pro_con=lock.newCondition();//用这个锁创建一个生产者监视器(返回绑定到此 Lock 实例的新 Condition 实例)
public void set(String name)
{
lock.lock();//获取锁
try
{
while(flag)
try{pro_con.await();}catch(InterruptedException e){}//捕捉await函数抛出的异常
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"........生产者........."+this.name);
flag=true;
con_con.signal();
}
finally//保证关闭锁
{
lock.unlock();//释放锁
}
}
public synchronized void get()
{
lock.lock();//获取锁
try
{
while(!flag)
try{con_con.await();}catch(InterruptedException e){}//捕捉await函数抛出的异常
System.out.println(Thread.currentThread().getName()+"..消费者.."+name);
flag=false;
pro_con.signal();
}
finally//保证关闭锁
{
lock.unlock();//释放锁
}
}
}
class Input implements Runnable
{
Resource r;
Input(Resource r)//构造函数
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("烤鸭");//生产
}
}
}
class Output implements Runnable//消费
{
Resource r;
Output(Resource r)//构造函数
{
this.r=r;
}
public void run()
{
while(true)
{
r.get();
}
}
}
class ResourceDemo2
{
public static void main(String[] args)
{
Resource r=new Resource();//创建资源
Input i=new Input(r);//创建线程任务
Output o=new Output(r);//创建线程任务
Thread t0=new Thread(i);//创建线程对象
Thread t1=new Thread(i);
Thread t2=new Thread(o);
Thread t3=new Thread(o);
t0.start();//开启线程
t1.start();
t2.start();
t3.start();
}
}