保护性暂停原理

什么是保护性暂停?

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

相关推荐
SL_staff27 分钟前
物模型三要素误用避坑指南:属性、事件、服务的正确建模逻辑
java
一条泥憨鱼31 分钟前
【Redis | 黑马点评】短信登录功能 源码深度分析
java·redis·后端·session·黑马点评
威哥爱编程36 分钟前
【AI全栈12-12】Spring Boot 3.x → 4.x 迁移实操:Jakarta 11、Jackson 3 与 AI 2.0
java·spring boot·后端
威哥爱编程41 分钟前
【AI全栈12-11】Spring Boot 把 AI 接口真正上线扛量:限流 / 降级 / 可观测
java·spring boot·后端
小蒜学长41 分钟前
基于SpringBoot+uni-app的闪洁家政系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·uni-app·家政服务
敲代码的彭于晏1 小时前
2026 K8s 零基础入门:手把手教你一步步搭建 Kubernetes 集群
java·运维·全栈
希洛兔1 小时前
状态模式详解:让对象随内部状态自动改变行为
java·设计模式·状态模式
需要8261 小时前
Spring Boot 启动流程:run() 里到底发生了什么
java·spring boot·后端
云絮.1 小时前
Mybatis(一)
java·数据库·mybatis
希洛兔2 小时前
里氏替换原则详解:子类必须能透明替换基类(含继承风险演示 + 正确重构 + JDK 案例)
java·里氏替换原则