Java 高并发编程详解 10.0 阻塞等待模式

阻塞等待模式

线程执行任务时条件不满足时挂起阻塞 等待条件满足时执行对应任务

实例:

public class GuardedQueue {
    // 定义存放Integer类型的queue
    private final LinkedList<Integer> queue = new LinkedList<>();
    // 定义队列的最大容量
    private final int LIMIT = 100;

    // 向queue中插入数据 当queue的元素数量大于最大容量,则会阻塞
    public void off(Integer data) throws InterruptedException{
        synchronized (this){
            // 判断queue的元素个数是否大于最大容量
            while (queue.size() >= LIMIT){
                // 阻塞
                this.wait();
            }
            // 没有则将数据放进queue
            queue.addLast(data);
            // 再唤醒阻塞休息室的线程
            this.notifyAll();
        }
    }

    // 获取queue中的元素 没有则阻塞等待queue中有有元素为止
    public Integer take() throws InterruptedException{
        synchronized (this){
            // 判断队列为空 阻塞
            while (queue.isEmpty()){
                this.wait();
            }
            // 不为空 取数据
            Integer first = queue.removeFirst();
            this.notifyAll();
            return first;
        }
    }
}

总结

这种模式是一种多线程基本的应用,使用Object类的wait()方法和notifyAll()方法来实现阻塞和唤醒执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值