保护性暂停原理

什么是保护性暂停?

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

相关推荐
杨凯凡几秒前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http
吴名氏.16 分钟前
Java转AI Agent教程(第十二周)检索与切分
java·开发语言·人工智能·ai·ai agent
瑞雪兆丰年兮1 小时前
JavaWeb-day10-SpringBootWeb案例
java·开发语言·javaweb·web
Rain的Java大神之路1 小时前
你背的Spring答案,全是5.x时代的:7.0.8源码一翻,80%的博客都过时了
java·后端·面试
这个昵称不容易2 小时前
考试报名系统的设计与实现(SpringBoot + MySQL + Vue 三角色平台)
java·springboot·毕设
Adellle2 小时前
设计模式指南 (Java 版) ㊁
java·开发语言·设计模式
特立独行的猫A3 小时前
cj-tauri:用仓颉写桌面与鸿蒙 PC 应用
java·后端·python
Lonely丶墨轩3 小时前
从一个 404 到负数 ID:第三方接口开发中的几次排错
java
聪明的笨猪猪3 小时前
实际工程问题:AI生成MyBatis批量操作的SQL超限与性能雪崩
java·经验分享·面试·ai编程
文丑颜不良啊3 小时前
LeetCode2501~2520题目解析
java·leetcode