用ReentrantLock和Condition实现生产者和消费者模式

可以使用wait和notify是一种生产者消费者模式实现,这是ReentrantLockCondition方式实现,下面是源码:

方法

构造方法

public ReentrantLock(); // 创建一个非公平锁

public ReentrantLock(boolean fair); // 创建一个公平或非公平锁

常用方法

返回值方法描述
voidlock()获取锁,当前线程会一直堵塞直到获取锁为止
voidlockInterruptibly()同上,但可以响应其它线程的 interrupt 操作
booleantryLock()尝试获取锁,锁空闲则直接获取到锁,并返回true,否则返回false。不会堵塞线程
booleantryLock(long timeout, TimeUnit unit)同上,但会等待指定时间
voidunlock()释放锁
ConditionnewCondition()返回一个绑定到此 Lock 的 Condition 实例

生产者代码:AppleCustomer

class AppleCustomer implements Runnable{
    //生产容器
    private AppleContainer container;

    public  AppleCustomer(AppleContainer container){
        this.container=container;
    }

    @Override
    public void run() {
        for(int i=0;i<10;i++){
            container.get();
        }
    }
}

消费者代码:AppleProducer

class AppleProducer implements Runnable{

    private AppleContainer container;

    public AppleProducer(AppleContainer container){
        this.container=container;
    }

    @Override
    public void run() {
        for(int i=0;i<10;i++){
            container.put("apple:"+i);
        }
    }
}

容器代码:AppleContainer

/**
 * 使用ReentrantLock实现生产者消费者
 * @Author zhangyukang
 * @Date 2020/2/21 09:44
 * @Version 1.0
 **/
public class AppleContainer {

    private static LinkedList<Object> container=new LinkedList<>();

    private static int size=0;

    private static final int MAX_SIZE=10;

    private ReentrantLock lock=new ReentrantLock();

    //消费者的条件
    private Condition customerCondition=lock.newCondition();

    //生产者的条件
    private Condition producerCondition=lock.newCondition();


    public void put(Object object){
        try {
            lock.lock();
            while (container.size()>=MAX_SIZE){
                try {
                    //生产者等待
                    producerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            container.add(object);
            size++;
            //可以准确的唤醒wait在当前对象的其他所用的消费者
            customerCondition.signalAll();
            System.out.println(Thread.currentThread().getName()+"生产:"+object+" size="+size);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public Object get(){
        try {
            lock.lock();
            while (container.size()==0){
                try {
                    //消费者等待
                    customerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object o = container.removeFirst();
            size--;
            //可以准确的唤醒wait在当前对象的其他所用的生产者
            producerCondition.signalAll();
            System.out.println(Thread.currentThread().getName()+"消费:"+o+" size="+size);
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }
}

测试代码:AppleCustomerProducerTest

class AppleCustomerProucerTest{
 public static void main(String[] args) {
        AppleContainer appleContainer = new AppleContainer();
        AppleProducer appleProducer = new AppleProducer(appleContainer);
        AppleCustomer appleCustomer = new AppleCustomer(appleContainer);
        for(int i=0;i<5;i++){
            new Thread(appleProducer,"生产者:"+i).start();
            new Thread(appleCustomer,"消费者:"+i).start();
        }
    }
}

输出

生产者:0生产:apple:0 size=1 生产者:0生产:apple:1 size=2 消费者:0消费:apple:0 size=1 消费者:0消费:apple:1 size=0 生产者:1生产:apple:0 size=1 生产者:1生产:apple:1 size=2 消费者:1消费:apple:0 size=1 消费者:1消费:apple:1 size=0 生产者:2生产:apple:0 size=1 生产者:2生产:apple:1 size=2 生产者:3生产:apple:0 size=3 生产者:3生产:apple:1 size=4 消费者:3消费:apple:0 size=3 消费者:3消费:apple:1 size=2 生产者:4生产:apple:0 size=3 生产者:4生产:apple:1 size=4 消费者:4消费:apple:0 size=3 消费者:4消费:apple:1 size=2 消费者:2消费:apple:0 size=1 消费者:2消费:apple:1 size=0

# Java   轮播列表   多线程  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×