class Resource
{
private String name;
private int count = 1;
private boolean flag;
//创建一个锁对象。
private final Lock lock = new ReentrantLock();
//获取一个该锁上的监视器。
private Condition con = lock.newCondition();
public void set(String name)//
{
//获取锁。
lock.lock();
try
{
while(flag)
try{con.await();}catch(InterruptedException e){}//t0(活-->wait) t1(活)
this.name = name + count;//馒头1 馒头2 馒头3
count++;
System.out.println(Thread.currentThread().getName()+".....生产者......"+this.name);//Thread-0 生产 馒头1
//Thread-0 生产 馒头2
//Thread-0 生产 馒头3
flag = true;
con.signalAll();//唤醒了消费者的其中一个线程
}
finally
{
//释放锁。
lock.unlock();
}
}
public void get()//
{
lock.lock();
try
{
while(!flag)
try{con.await();}catch(InterruptedException e){}//t2 t3
System.out.println(Thread.currentThread().getName()+".........消费者......"+this.name);//Thread-2 消费 馒头1
flag = false;
con.signalAll();
}
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.get();
}
}
}
class ProConDemo3
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
//两个线程负责生产。
Thread t0 = new Thread(pro);
Thread t1 = new Thread(pro);
//两个线程负责消费。
Thread t2 = new Thread(con);
Thread t3 = new Thread(con);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
休眠状态具有执行资格和执行权,而阻塞状态只有执行资格没有执行权了
下面给你给图看看:
|
|