zoukankan      html  css  js  c++  java
  • AQS 与 LockSupport

    一、结构

    Lock的实现类其实都是构建在AbstractQueuedSynchronizer上,每个Lock实现类都持有自己内部类Sync的实例

      

    二、LockSupport

    Basic thread blocking primitives for creating locks and other synchronization classes.

    This class associates, with each thread that uses it, a permit (in the sense of the Semaphore class). A call to park will return immediately

    if the permit is available, consuming it in the process; otherwise it may block. A call to unpark makes the permit available, if it was not

    already available. (Unlike with Semaphores though, permits do not accumulate. There is at most one.)

    每个使用LockSupport的线程都和一个permit相关联, 如果permit可用,调用park()会立即返回。

    1、park和unpark的灵活之处:unpark函数可以先于park调用

    wait/notify机制有个很蛋疼的地方,比如线程B要用notify通知线程A,那么线程B要确保线程A已经在wait调用上等待了,否则线程A可能永远都在等待。

    另外,是调用notify,还是notifyAll?

    notify只会唤醒一个线程,如果有两个线程在同一个对象上wait等待,那么又悲剧了。为了安全起见,貌似只能调用notifyAll了。

    park/unpark模型真正解耦了线程之间的同步,线程之间不再需要一个Object或者其它变量来存储状态,不再需要关心对方的状态。

      

    2、public static void park()

    Disables the current thread for thread scheduling purposes unless the permit is available.

    If the permit is available then it is consumed and the call returns immediately; otherwise the current thread becomes disabled for thread

    scheduling purposes and lies dormant until one of three things happens:

    1.Some other thread invokes unpark with the current thread as the target

    2.Some other thread interrupts the current thread

    3.The call spuriously (that is, for no reason) returns (虚假唤醒(spurious wakeup))

    This method does not report which of these caused the method to return. Callers should re-check the conditions which caused the thread

    to park in the first place. Callers may also determine, for example, the interrupt status of the thread upon return.

    3、什么是虚假唤醒(spurious wakeup)

    参考:

    再谈AbstractQueuedSynchronizer:独占模式

  • 相关阅读:
    基于Text-CNN模型的中文文本分类实战 流川枫 发表于AI星球订阅
    SQL Server 定时执行SQL语句的方法
    linq 根据指定条件返回集合中不重复的元素
    asp.net mvc ChildActionOnly 和ActionName的用法
    C# 让枚举返回字符串
    EF中使用SQL语句或存储过程
    Sql Server系列:视图
    C# 获取web.config配置文件
    C# 在EF中直接运行SQL命令
    c# mvc 获取 HtmlHelper 表达式值和时间格式化 去边框
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3996479.html
Copyright © 2011-2022 走看看