wait notifyAll ReentrantLock Condition 实现同步容器

  • wait notifyAll 实现同步容器
public class Container1<T > {
    final private LinkedList<T> list = new LinkedList<>();
    final private int Max = 10;
    private int count = 0;

    public synchronized void put(T t){
        while (list.size() == Max){ // while if 区别
            try {
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        list.add(t);
        ++ count;
        this.notifyAll();// 通知消费者线程消费
    }
    public synchronized T get(){
        T t = null;
        while (list.size() == 0){
            try {
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        t = list.removeFirst();
        count -- ;
        this.notifyAll();//通知生产者生产
        return t;
    }
}

注意: wait 会释放锁, notify不会释放锁

为什么使用 while 而不使用 if ?

while每次都会检查完条件再往下执行,if 不会

 

  • ReentrantLock Condition 实现同步容器
public class Container2<T > {
    final private LinkedList<T> list = new LinkedList<>();
    final private int Max = 10;
    private int count = 0;
    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(T t){
        try {
            lock.lock();
            while (list.size() == Max){ // while if 区别
                producer.await();
            }
            list.add(t);
            ++ count;
            consumer.signalAll();// 通知消费者线程消费
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public T get(){
        T t = null;
        try {
            lock.lock();
            while (list.size() == 0){
                consumer.await();
            }
            t = list.removeFirst();
            count -- ;
            producer.signalAll();//通知生产者生产
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return t;
    }
}

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值