生产者-消费者问题:
生产者向产品区里放产品,当产品区里满了,生产者需要等待;消费者从产品区里取产品腾出容量,生产者可继续生产,当产品区里空了,需要等待生产者生产。
public class ProducerAndConsumer
{
//创建缓冲区
private static Buffer buffer = new Buffer();
public static void main(String[] args)
{
//创建生产者
Thread producer = new Thread(new Producer());
//创建消费者
Thread consumer = new Thread(new Consumer());
//开始生产
consumer.start();
//开始消费
producer.start();
}
//消费者线程
static class Consumer implements Runnable
{
public void run(){
try{
while(true){
//消费
buffer.poll();
Thread.sleep(1000));
}
}catch(InterruptedException ex){}
}
}
//生产者线程
static class Producer implements Runnable
{
public void run(){
try{
while(true){
//生产
buffer.push(new Random().nextInt(20));
Thread.sleep(1000);
}
}catch(InterruptedException ex){}
}
}
}
//缓冲池
class Buffer
{
//创建锁
private static Lock lock = new ReentrantLock();
//条件1:缓冲池为空
private static Condition empty = lock.newCondition();
//条件2:缓冲池为满
private static Condition full = lock.newCondition();
//缓冲池大小
private static final int size = 10;
//缓冲池
private Queue<Integer> queue = new LinkedList<Integer>();
//消费
public void poll(){
lock.lock();
try{
while(queue.size() == 0){
System.out.println("无产品可消费,等待生产者生产。");
empty.await();
}
int num = queue.poll();
System.out.println("出售商品:" + num);
//通知生产者:仓库有位置了
full.signal();
}catch(InterruptedException ex){
}finally{
lock.unlock();
}
}
//生产
public void push(int num){
lock.lock();
try{
//库存不能大于仓库额定容量:10
while(queue.size() == 10){
System.out.println("Wait for consumer:");
full.await();
}
//商品入库
queue.offer(num);
System.out.println("生产商品:" + num);
//通知消费者:商品已经来了
empty.signal();
}catch(InterruptedException ex){
}finally{
lock.unlock();
}
}
}