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:独占模式

  • 相关阅读:
    可视化百分比数据,Excel图表展示小技巧
    巧用宏录制,轻松制作Excel简易查询小系统
    Excel也能制作电子印章,你见过吗?学会了职场不求人
    ​21个Shift组合快捷键,学会了想加班都难
    Excel中关于日期时间的小知识小技巧,你还记得多少?
    自动添加单元格边框,Excel有妙招,两个技巧任意选
    [asp.net] 通过JS实现对treeview控件的复选框单选控制。
    编译器把getset访问器编译成了方法get_method()/set_method()
    sql MERGE
    动态添加特性
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3996479.html
Copyright © 2011-2022 走看看