保护性暂停原理

什么是保护性暂停?

保护性暂停(Guarded Suspension)是一种常见的线程同步设计模式,常用于解决 生产者-消费者问题 或其他需要等待条件满足后再继续执行的场景。通过这种模式,一个线程在执行过程中会检查某个条件是否满足,如果不满足,就进入等待状态,直到另一个线程通知条件已满足

无非就是有点类似一个空盘子,一个消费者和生产者场景有点类似。有就唤醒消费者消费,没有消费者就等待。

1、示例:

public class test2 {
    public static void main(String[] args) {
        GuardeObject guardeObject = new GuardeObject();
        new Thread(() -> {
            Object o = guardeObject.get();
        }).start();

        new Thread(() -> {
            guardeObject.comolete(Arrays.asList(1,2,3));
        }).start();

    }
}
class GuardeObject{
    private Object response;
    // 获取结果
    public Object get() {
        synchronized (this) {
            while (response == null) {
                try {
                    System.out.println("response == null");
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("输出结果");
            return response;
        }
    }

    // 产生结果
    public void comolete(Object response) {
        synchronized (this) {
            this.response = response;
            try {
                System.out.println("产生结果");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.notifyAll();
        }
    }
}

2、保护性暂停超时返回示例

   // 获取结果
    public Object get(long timeout) {
        synchronized (this) {
            long begin = System.currentTimeMillis();
            long passTime = 0;
            while (response == null) {
                long waitTime = timeout - passTime;
                if (waitTime <= 0) break;
                try {
                    System.out.println("response == null");
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            passTime = System.currentTimeMillis() - begin;
            System.out.println("输出结果");
            return response;
        }
    }

3、join源码

在这里插入图片描述

4、总结

保护性暂停的超时等待应用于 join()方法中,可用于超时返回结果。保护性暂停的核心:在于等待线程在某个条件不满足时进入等待状态,并通过其他线程的通知机制在条件满足时继续执行

觉得有帮助的话,点个赞或关注再走呗。

什么是精神内耗?
简单地说,就是心理戏太多,自己消耗自己。
所谓:
言未出,结局已演千百遍;
身未动,心中已过万重山;
行未果,假想灾难愁不展;
事已闭,过往仍在脑中演。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的小熊猫_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值