本帖最后由 刘文飞 于 2012-11-17 21:05 编辑
import java.util.concurrent.locks.*;
class Resource{
private int count;
private boolean flag;
private Lock lock = new ReentrantLock();
private Condition condition_pro = new lock.newCondition();//多了个new
private Condition condition_con = new lock.newCondition();
public void produce() throws InterruptedException
{
lock.lock();
try{
while(flag)
{
condition_pro.await();
}
System.out.println(Thread.currentThread().getName() + "---生产---" + ++count );
flag = true;
condition_con.signal();
}
finally
{
lock.unlock();
}
}
public void consume() throws InterruptedException
{
lock.lock();
try
{
while(!flag)
{
condition_con.await();
}
System.out.println(Thread.currentThread().getName() + "---消费---" + count--);
flag = false;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resource res;
public Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable
{
private Resource res;
public Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class ProducerConsumerLockDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);
Thread t5 = new Thread(con);
Thread t6 = new Thread(con);
Thread t7 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
} |
|