生产者 - 消费者模型

1. 使用syncronize实现

    static Object[] items = new Object[100];
    static int takePoint = 0, putPoint = 0;
    static AtomicInteger cnt = new AtomicInteger(0);

    public synchronized static void produce(Object o) throws InterruptedException {
        while(cnt.get() == items.length) {  //如果写队列满了,阻塞
            Thread.sleep(1000);
        }
        items[putPoint++] = o;
        cnt.getAndIncrement();
        if(putPoint == items.length) putPoint = 0;
    }

    public synchronized static Object consume() throws InterruptedException {
        while(cnt.get() == 0) {    //如果读队列满了,阻塞
            Thread.sleep(1000);
        }
        Object res = items[takePoint++];
        cnt.getAndDecrement();
        if(takePoint == items.length) takePoint = 0;
        return res;
    }

2. 基于reentrantlock 和 condition实现

    static final ReentrantLock lock = new ReentrantLock();
    static final Condition read = lock.newCondition(), write = lock.newCondition();
    static Object[] items = new Object[100];
    static AtomicInteger cnt = new AtomicInteger(0), takePoint = new AtomicInteger(0),
    putPoint = new AtomicInteger(0);

    public static void produce(Object o) throws InterruptedException {
        lock.lock();
        try {
            if(cnt.get() == items.length) {
                write.await();  //如果写队列满了,写线程阻塞
            }
            items[putPoint.get()] = o;
            if(putPoint.getAndIncrement() + 1 == items.length) putPoint.set(0);
            cnt.getAndIncrement();
            read.signal();    //通知读线程
        }finally {
            lock.unlock();
        }

    }

    public static Object consume() throws InterruptedException {
        lock.lock();
        Object res = null;
        try {
            if(cnt.get() == 0) {
                read.await();   //如果读队列空了,读线程阻塞
            }
            res = items[takePoint.get()];
            cnt.getAndDecrement();
            if(takePoint.getAndIncrement() + 1 == items.length) takePoint.set(0);
            write.signal();   //通知写线程
            return res;
        }finally {
            lock.unlock();
        }

    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值