保护性暂停原理

什么是保护性暂停?

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

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

1、正常示例:

java 复制代码
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、保护性暂停超时返回示例

java 复制代码
   // 获取结果
    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()方法中,可用于超时返回结果。保护性暂停的核心:在于等待线程在某个条件不满足时进入等待状态,并通过其他线程的通知机制在条件满足时继续执行

相关推荐
ZC跨境爬虫2 分钟前
跟着 MDN 学JavaScript day_5:技能测试——变量实战
java·开发语言·前端·javascript
瑞雪兆丰年兮5 分钟前
[0开始学Java|第二十四天]集合(Map&可变参数&集合工具类Collections)
java·开发语言·map·collections
鱼鳞_9 分钟前
苍穹外卖-Day12(数据统计)
java·spring boot
phltxy11 分钟前
Spring AI Alibaba 多模态应用开发实践
java·人工智能·spring
garmin Chen17 分钟前
Prompt工程入门:让AI按你的要求工作(2)--Prompt 高阶优化与结构化设计
java·人工智能·python·ai·prompt
GesLuck17 分钟前
Node-RED企业微信发送—群文件
android·java·企业微信
whatever who cares21 分钟前
android中fragment demo举例
android·java·开发语言
西凉的悲伤25 分钟前
Guava类库——Range连续区间
java·算法·guava
武子康26 分钟前
Java-17 深入浅出MyBatis Mapper Proxy 源码解析:从 getMapper 到 invoke 的完整链路
java·后端
plainGeekDev26 分钟前
CountDownTimer → Flow
android·java·kotlin