生产者消费者模型简单实现(java)

主要使用了juc中的Lock和Condition接口,代码如下:

public class Storage {
    private static final int SIZE=100;
    private LinkedList linkedList=new LinkedList<>();
    private final Lock lock=new ReentrantLock();
    private final Condition full=lock.newCondition();
    private final Condition empty=lock.newCondition();
    //生产
    public void produce(){

        lock.lock();
        while(linkedList.size()==SIZE) {
            try {
                full.await();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        linkedList.add(new Object());
        empty.signalAll();
        lock.unlock();

    }

    //消费
    public void consume(){
        lock.lock();
        while(linkedList.size()==0) {
            try {
                empty.await();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        linkedList.remove();
        full.signalAll();
        lock.unlock();
    }
}
 

                            
                        
                    
                    
                    

你可能感兴趣的:(生产者消费者模型简单实现(java))