【多线程开发 4】从源码学习LockSupport

从源码学习LockSupport

2024年6月30日

大家好啊,好久没写博客了,今天打算写一下,讲一下JUC里面LockSupport这个类。

这个是一个工具类,实际上也是为了线程通信开发的。它的源码比较短,也只引用了Unsafe一个类。所以我们可以先看下他的源码:

类注释

他的类注释如下:

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.) Reliable usage requires the use of volatile (or atomic) variables to control when to park or unpark. Orderings of calls to these methods are maintained with respect to volatile variable accesses, but not necessarily non-volatile variable accesses.
Methods park and unpark provide efficient means of blocking and unblocking threads that do not encounter the problems that cause the deprecated methods Thread. suspend and Thread. resume to be unusable for such purposes: Races between one thread invoking park and another thread trying to unpark it will preserve liveness, due to the permit. Additionally, park will return if the caller’s thread was interrupted, and timeout versions are supported. The park method may also return at any other time, for “no reason”, so in general must be invoked within a loop that rechecks conditions upon return. In this sense park serves as an optimization of a “busy wait” that does not waste as much time spinning, but must be paired with an unpark to be effective.
The three forms of park each also support a blocker object parameter. This object is recorded while the thread is blocked to permit monitoring and diagnostic tools to identify the reasons that threads are blocked. (Such tools may access blockers using method getBlocker(Thread).) The use of these forms rather than the original forms without this parameter is strongly encouraged. The normal argument to supply as a blocker within a lock implementation is this.
These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. The park method is designed for use only in constructions of the form:

while (!canProceed()) {   // ensure request to unpark is visible to other threads ...   LockSupport. park(this);
}

where no actions by the thread publishing a request to unpark, prior to the call to park, entail locking or blocking. Because only one permit is associated with each thread, any intermediary uses of park, including implicitly via class loading, could lead to an unresponsive thread (a “lost unpark”).
Sample Usage. Here is a sketch of a first-in-first-out non-reentrant lock class:

class FIFOMutex {private final AtomicBoolean locked = new AtomicBoolean(false);private final Queue<Thread> waiters = new ConcurrentLinkedQueue<>();public void lock() {boolean wasInterrupted = false;// publish current thread for unparkerswaiters.add(Thread.currentThread());// Block while not first in queue or cannot acquire lockwhile (waiters.peek() != Thread.currentThread() || !locked.compareAndSet(false, true)) {LockSupport.park(this);// ignore interrupts while waiting       if (Thread.interrupted()) wasInterrupted = true;}waiters.remove();// ensure correct interrupt status on returnif (wasInterrupted)Thread.currentThread().interrupt();}public void unlock() {locked.set(false);LockSupport.unpark(waiters.peek());}static {     // Reduce the risk of "lost unpark" due to classloadingClass<?> ensureLoaded = LockSupport.class;}
}

第一段文本大意为:

用于创建锁和其他同步类的基本线程阻塞原语。这个类与使用它的每个线程关联一个许可证(在信号量类的意义上)。如果许可证可用,将立即返回停车呼叫,并在此过程中消耗许可证;否则可能会堵塞。如果许可证尚未可用,则调用取消停车使其可用。(但与信号量不同的是,许可证不会累积。最多只有一个。)可靠的使用需要使用易失性(或原子)变量来控制何时停放或取消停放。调用这些的顺序

其实就是对想要枷锁的信息加上一个许可,提前给他许可再消费许可,还是代码走到消费许可后再拿到许可都可以,。

第二段文本大意为:

如果在调用park之前,线程没有发布请求取消park的操作,则会导致锁定或阻塞。因为每个线程只关联一个许可证,任何中间使用park(包括通过类加载隐式地使用)都可能导致线程无响应(“丢失的unpark”)。
样品使用。这是一个先进先出的不可重入锁类的草图:

就是根据第二块代码展示LockSupport具体怎么使用。

代码细节

unpark(Thread thread)

给对应thread发放许可。如果线程被LocjSupport的park()方法阻塞时,使用该方法会被立刻释放运行,如果没有阻塞,则使用该方法发放许可证明时,在下一次调用park()方法,则会直接运行不被阻塞。

park(Object blocker)

会向当前线程请求许可,没有许可就会阻塞,除非发生以下三种情况之一:

  • 其他线程以当前线程为目标调用unpark
  • 其他线程中断当前线程
  • 调用返回

但是park方法不能看出来是哪一个原因导致线程可以重新运行。需要调用的人自己写代码看,例如,线程返回时的中断状态。

parkNanos(Object blocker, long nanos)

和park方法一样,但是有时间限制,到了时间限制也会停止阻塞。

getBlocker(Thread t)

提供阻塞线程t的正在被阻塞的park方法是谁调用的,但是线程不安全,拿到这个对象操作的时候可能也已经被unpark了也说不定。

park()

直接禁用当前线程。

private LockSupport() {} // Cannot be instantiated.

LockSupport不能被初始化,只能使用LockSupport进行开发

setCurrentBlocker(Object blocker)

该方法可以做到在blocker使用park()方法之前会调用该方法,可以做到一些分析的作用。

总结

这个方法比较简单,但是比较方便进行线程间通信。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/38658.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

机器学习——强化学习状态值函数V和动作值函数Q的个人思考

最近在回顾《西瓜书》的理论知识&#xff0c;回顾到最后一章——“强化学习”时对于值函数部分有些懵了&#xff0c;所以重新在网上查了一下&#xff0c;发现之前理解的&#xff0c;包括网上的大多数对于值函数的描述都过于学术化、公式化&#xff0c;不太能直观的理解值函数以…

SQL常用经典语句大全

SQL经典语句大全 一、基础 1、说明&#xff1a;创建数据库 CREATE DATABASE database-name 2、说明&#xff1a;删除数据库 drop database dbname 3、说明&#xff1a;备份sql server — 创建 备份数据的 device USE master EXEC sp_addumpdevice ‘disk’, ‘testBack’, ‘c:…

macos Automator自动操作 app, 创建自定义 应用程序 app 的方法

mac内置的这个 自动操作 automator 应用程序&#xff0c;可以帮助我们做很多的重复的工作&#xff0c;可以创建工作流&#xff0c; 可以录制并回放操作&#xff0c; 还可以帮助我们创建自定的应用程序&#xff0c;下面我们就以创建一个自定义启动参数的chrome.app为例&#xff…

C语言 求数列 S(n) = a + aa + aaa + …aa…a (n 个 a)的和

求数列S(n)aaaaaa…aa…a(n个a)之值&#xff0c;其中a是一个数字&#xff0c;n表示a的位数&#xff0c;n由键盘输入。例如222222222222222&#xff08;此时n5&#xff09; 这个程序读取用户输入的一个数字 a 和一个正整数 n&#xff0c;计算并输出数列 S(n) 的值。 #include …

cube-studio 开源一站式云原生机器学习/深度学习/大模型训练推理平台介绍

全栈工程师开发手册 &#xff08;作者&#xff1a;栾鹏&#xff09; 一站式云原生机器学习平台 前言 开源地址&#xff1a;https://github.com/tencentmusic/cube-studio cube studio 腾讯开源的国内最热门的一站式机器学习mlops/大模型训练平台&#xff0c;支持多租户&…

绘图黑系配色

随便看了几篇小论文&#xff0c;里面的黑配色挺喜欢的&#xff0c;虽然平时SCI系配色用的多&#xff0c;但看到纯黑配色与黑加蓝配色&#xff0c;那就是我最心上的最优style。

一文了解IP地址冲突的起因与解决方案

IP 地址冲突是困扰网络管理员影响网络的正常运行的常见因素。深入理解并有效解决 IP 地址冲突故障对于维护网络的高效稳定运行具有重要意义。 一、IP 地址冲突的原因 &#xff08;一&#xff09;人为配置错误 网络用户在手动配置 IP 地址时&#xff0c;对网络配置了解不多用户…

OpenGL3.3_C++_Windows(23)

伽ga马校正 物理亮度 光子数量 线性空间&#xff1a;光子数(亮度&#xff09;和颜色值的线性关系人眼感知的亮度&#xff1a;对比较暗的颜色变化更敏感&#xff0c;感知亮度基于人的感觉非线性空间&#xff1a;光子数(亮度&#xff09;和 颜色值^2.2&#xff0c;恰好符合屏幕…

一些项目的说明

这是一个管理系统&#xff0c;比较缝合&#xff0c;可能想到什么有用的功能就写&#xff0c;也没太多的针对性&#xff0c;需要的功能可以自己拆解去用&#xff0c;也欢迎往上添加新功能。 业余玩家&#xff0c;代码有空就写。 项目相关的业务设计写在CSDN博客里。用户IDYuboc…

为什么我学个 JAVA 就已经耗尽所有而有些人还能同时学习多门语言

在开始前刚好我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「JAVA的资料从专业入门到高级教程」&#xff0c; 点个关注在评论区回复“888”之后私信回复“888”&#xff0c;全部无偿共享给大家&#xff01;&#xff01;&#xff01;我的入门语言是C&#xff0c…

Android InputChannel连接

InputChannel是InputDispatcher 和应用程序 (InputTarget) 的通讯桥梁&#xff0c;InputDispatcher 通知应用程序有输入事件&#xff0c;通过InputChannel中的socket进行通信。 连接InputDispatcher和窗口 WinodwManagerService:addwindow: WMS 添加窗口时&#xff0c;会创建…

互联网场景下人脸服务基线方案总结

1.简介 1.1目的 在过去的一段时间里&#xff0c;因为听见业务对人脸服务方案的需求&#xff0c;针对网络视频中关键人物定位的检索任务&#xff0c;完成了基于互联网场景的人脸基线服务的构建。本文档是对当前基线服务以后之后解决方案的优化进行总结。 1.2范围 本文档描述的人…

c++读取文件时出现中文乱码

原因&#xff1a;UTF-8格式不支持汉字编码 解决&#xff1a;改成ANSI&#xff0c;因为ANSI编码支持汉字编码

Python学习路线图(2024最新版)

这是我最开始学Python时的一套学习路线&#xff0c;从入门到上手。&#xff08;不敢说精通&#xff0c;哈哈~&#xff09; 一、Python基础知识、变量、数据类型 二、Python条件结构、循环结构 三、Python函数 四、字符串 五、列表与元组 六、字典与集合 最后再送给大家一套免费…

FFmpeg开发笔记(四十二)使用ZLMediaKit开启SRT视频直播服务

《FFmpeg开发实战&#xff1a;从零基础到短视频上线》一书在第10章介绍了轻量级流媒体服务器MediaMTX&#xff0c;通过该工具可以测试RTSP/RTMP等流媒体协议的推拉流。不过MediaMTX的功能实在是太简单了&#xff0c;无法应用于真实直播的生产环境&#xff0c;真正能用于生产环境…

KVB App:中国制造业数据支撑澳元,分析师预计挑战0.6750阻力

摘要&#xff1a; 中国6月财新制造业PMI上升至51.8&#xff0c;反映出制造业生产经营活动的持续扩张。这一数据不仅高于预期&#xff0c;还为澳元提供了强有力的支撑。技术分析显示&#xff0c;澳元/美元可能会在短期内挑战0.6750阻力水平。 中国制造业数据解析 6月&#xff0…

python异常、模块与包

目录 了解异常异常的捕获方法python模块python包安装第三方包 了解异常 什么是异常 当检测到一个错误时&#xff0c;python解释器就无法继续执行了&#xff0c;反而出现了一些错误的提示&#xff0c;这就是所谓的“异常”&#xff0c;也就是我们常说的BUG bug单词的诞生 早期…

Python入门-基本数据类型-常用的字符串方式

1.字符串大小转换 方法说明sname.title()将字符串中的每个单词首字母大写sname.lower()将字符串中所有字母转为小写sname.upper()将字符串中所有字母转为大写 2.判断字符内容 方法说明sname.isupper()当字符串中所有字符都是大写时返回True&#xff0c;否则返回Falsesname.i…

Python tkinter: 开发一个目标检测GUI小程序

程序提供了一个用户友好的界面&#xff0c;允许用户选择图片或文件夹&#xff0c;使用行人检测模型进行处理&#xff0c;并在GUI中显示检测结果。用户可以通过点击画布上的检测结果来获取更多信息&#xff0c;并使用键盘快捷键来浏览不同的图片。 一. 基本功能介绍 界面布局&am…

智芯开发板----时钟的使用

一、开发板时钟概述 介绍 Z20K11xM 的时钟结构&#xff0c;分布以及各个外设时钟源的选择。SCC 模块用于选择系统时钟&#xff0c;产生 core clock、bus clock 和 flash clock&#xff0c;分 别用于驱动 core 及高速外设、普通外设和 flash。PARCC 模块用于单独设置 每个外设的…