保护性暂停原理

什么是保护性暂停?

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

相关推荐
BD_Marathon6 分钟前
IDEA创建多级包时显示在同一行怎么办
java·ide·intellij-idea
亓才孓6 分钟前
【Exception】CONDITIONS EVALUATION REPORT条件评估报告
java·开发语言·mybatis
硅基动力AI31 分钟前
如何判断一个关键词值不值得做?
java·前端·数据库
重生之后端学习1 小时前
78. 子集
java·数据结构·算法·职场和发展·深度优先
那起舞的日子2 小时前
斐波那契数列
java·算法
想用offer打牌2 小时前
一站式了解接口防刷(限流)的基本操作
java·后端·架构
姜源Jerry3 小时前
【Trae】Trae IDE&SOLO浅尝
java·ide·ai
宇木灵3 小时前
C语言基础-三、流程控制语句
java·c语言·前端
小杨互联网4 小时前
项目CyberScan Pro jar软件安全成分分析插件
java·jar·软件成分分析·jar安全分析
组合缺一4 小时前
Java 版 Claude Code CLI 来了!(国产开源项目)Solon Code CLI 发布
java·ai·开源·llm·solon·cli·claudecode