就像这个生产者消费者问题,一边生产,一变消费。但他们操纵的是同一个对象,所以就需要这个对象唯一。在Resourse使用饿汉式创建了对象,在Producter和Consumer中获取这个对象操作它。
import java.util.concurrent.locks.*;
class ProducerConsumerDemo2
{
public static void main(String[] args)
{
new Thread(new Producer()).start();
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
new Thread(new Consumer()).start();
}
}
class Resourse
{
private static final Resourse r=new Resourse();
private Resourse(){}
public static Resourse getRes(){
return r;
}
private String name;
private int count=0;
private boolean state=true;
private Lock lock=new ReentrantLock();
private Condition condition_pro =lock.newCondition();
private Condition condition_con =lock.newCondition();
public void set(String name) throws InterruptedException
{
lock.lock();
try
{
while(!state)
condition_pro.await();
this.name=name+"-----"+count++;
System.out.println(Thread.currentThread().getName()+"。。。。生产者。。。"+this.name);
state=false;
condition_con.signal();
}
finally
{
lock.unlock();//释放锁的动作一定要执行
}
}
public void get() throws InterruptedException
{
lock.lock();
try
{
while(state)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"。。。。消费者。。。。。。。。"+this.name);
state=true;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
Resourse r=Resourse.getRes();
public void run(){
while(true)
{
try
{
r.set("商品");
}
catch (InterruptedException e)
{
}
}
}
}
class Consumer implements Runnable
{
Resourse r=Resourse.getRes();
public void run(){
while(true)
{
try
{
r.get();
}
catch (InterruptedException e)
{
}
}
}
}
|