• 同步模式之保护性暂停模式


    1. Guarded Suspension:一个线程需要等待另一个线程的执行结果

    2. 理解

    • 一个线程需要将结果传递给另一个线程,将这两个线程关联到到同一个 GuardedObject 

    • 如果需要源源不断地传递结果,需要使用消息队列(生产者-消费者模型)
    • JDK 中,join 的实现、Future 的实现用的都是保护性暂停模式
    • 因为要等待,所以算作同步模式

    3. 实现

    • 创建两个线程和一个守护对象,线程 1 wait 等待下载结果 response,线程 2 执行下载,下载完成将结果赋值给 GuardedObject 的 response 属性,然后 notify 唤醒线程 1,线程 1 被唤醒,继续执行,两个线程通过 GuardedObject 传递要用的结果

    4. 优点

    • join 需要等一个线程运行结束了才能得到该线程的结果
    • join 等待结果的变量只能是全局的,GuardedObject 可以是局部的

    5. 扩展 1

    • 超时退出:wait(timeout) 只等待一段时间,如果超时了还没有获取到结果就直接退出循环

    (resposne 是下载完成之后赋值的,response 不为空之后就可以退出循环,返回 res) 

    6. join 的原理:保护性暂停是等待一个线程的结果,join 是等待一个线程的结束

    • 就是应用了保护性暂停模式,如果线程还存活(对应上面的下载结果 response == null)且未超时就一直等待,如果超时了(还没有得到结果)就退出循环
    1. /**
    2. * Waits at most {@code millis} milliseconds for this thread to
    3. * die. A timeout of {@code 0} means to wait forever.
    4. *
    5. *

      This implementation uses a loop of {@code this.wait} calls

    6. * conditioned on {@code this.isAlive}. As a thread terminates the
    7. * {@code this.notifyAll} method is invoked. It is recommended that
    8. * applications not use {@code wait}, {@code notify}, or
    9. * {@code notifyAll} on {@code Thread} instances.
    10. *
    11. * @param millis
    12. * the time to wait in milliseconds
    13. *
    14. * @throws IllegalArgumentException
    15. * if the value of {@code millis} is negative
    16. *
    17. * @throws InterruptedException
    18. * if any thread has interrupted the current thread. The
    19. * interrupted status of the current thread is
    20. * cleared when this exception is thrown.
    21. */
    22. public final synchronized void join(long millis)
    23. throws InterruptedException {
    24. long base = System.currentTimeMillis();
    25. long now = 0;
    26. if (millis < 0) {
    27. throw new IllegalArgumentException("timeout value is negative");
    28. }
    29. if (millis == 0) {
    30. while (isAlive()) {
    31. wait(0);
    32. }
    33. } else {
    34. while (isAlive()) {
    35. long delay = millis - now;
    36. if (delay <= 0) {
    37. break;
    38. }
    39. wait(delay);
    40. now = System.currentTimeMillis() - base;
    41. }
    42. }
    43. }

    7. 扩展2:生产者消费者节耦 

  • 相关阅读:
    JDK -- Stream使用
    选择适合你的编程语言
    外包干了3个月,技术退步明显。。。。。
    C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别
    手写简易Spring框架
    Worthington木瓜蛋白酶化学性质和特异性
    JavaScript进阶:js的一些学习笔记-this指向,call,apply,bind,防抖,节流
    光纤环形镜FBG传感器
    蓝海创意云·11月大事记 || 12月,暖心相伴
    速览 NFT 期权赛道代表项目与发展前景
  • 原文地址:https://blog.csdn.net/m0_74059961/article/details/140052907