当前位置:网站首页>"Ask every day" how locksupport realizes thread waiting and wakeup
"Ask every day" how locksupport realizes thread waiting and wakeup
2022-07-25 14:53:00 【Senior fishing Engineer】
wait/notify Implement thread communication
How about thread communication , The more traditional way is to use synchronized Keyword after obtaining the object lock , combination Object Self contained wait/notify Method to implement .
A simple example is as follows :
public static void main(String[] args) throws InterruptedException {
ObjectTar objectTar = new ObjectTar();
new WaitThread("WaitThread", objectTar).start();
Thread.sleep(1000);
new NotifyThread("NotifyThread", objectTar).start();
}
@Data
private static class ObjectTar {
private String name;
}
private static class WaitThread extends Thread {
final ObjectTar objectTar;
WaitThread(String name, ObjectTar tar) {
super(name);
this.objectTar = tar;
}
@Override
public void run() {
synchronized (objectTar) {
System.out.println(getName() + " Get the lock , Prepare to execute your own business logic ");
if (StringUtils.isEmpty(objectTar.getName())) {
System.out.println(getName() + " Find that the current situation can not meet their own requirements , Then perform objectTar.wait()");
try {
objectTar.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " from objectTar.wait() return , Complete your business logic ," + objectTar.getName());
}
}
}
private static class NotifyThread extends Thread {
final ObjectTar objectTar;
NotifyThread(String name, ObjectTar tar) {
super(name);
this.objectTar = tar;
}
@Override
public void run() {
synchronized (objectTar) {
System.out.println(getName() + " Get the lock , It's done objectTar Of name initialization ");
objectTar.setName(" Braised chicken ");
objectTar.notifyAll();
System.out.println(getName() + " After execution notify after , Continue to execute your business logic ");
}
}
}
WaitThread Get the lock , Prepare to execute your own business logic
WaitThread Find that the current situation can not meet their own requirements , Then perform objectTar.wait()
NotifyThread Get the lock , It's done objectTar Of name initialization
NotifyThread After execution notify after , Continue to execute your business logic
WaitThread from objectTar.wait() return , Complete your business logic , Braised chicken
wait and notify The notification implementation mechanism of is shown in the figure below , Because this is not the pig's feet of this article , So don't start talking :)
Through the above example , Can be found using wait/notify To realize the communication mechanism, there are three obvious shortcoming :
- wait/notify All are Object The method in , Before using these two methods, you must obtain the lock of this object , This limits its application , That is, it must be in the synchronized code block .
- notify Is to wake up a thread at random ,notifyAll Yes, wake up all threads , There is no way to specify a thread wake .
- If notify Execute before ,wait After the execution , Get into wait If there is a problem with the judgment logic of , Then the thread may be blocked all the time
Use LockSupport Implement thread communication
A simple example implementation wait/notify Same effect
public static void main(String[] args) throws InterruptedException {
ObjectTar objectTar = new ObjectTar();
ParkThread parkThread = new ParkThread("ParkThread", objectTar);
parkThread.start();
Thread.sleep(1000);
// Notice the introduction of parkThread
new UnParkThread("UnParkThread", objectTar, parkThread).start();
}
@Data
private static class ObjectTar {
private String name;
}
private static class ParkThread extends Thread {
final ObjectTar objectTar;
ParkThread(String name, ObjectTar tar) {
super(name);
this.objectTar = tar;
}
@Override
public void run() {
System.out.println(getName() + " Get the lock , Prepare to execute your own business logic ");
if (StringUtils.isEmpty(objectTar.getName())) {
System.out.println(getName() + " Find that the current situation can not meet their own requirements , Then perform LockSupport.park()");
LockSupport.park();
}
System.out.println(getName() + " from LockSupport.park() return , Complete your business logic ," + objectTar.getName());
}
}
private static class UnParkThread extends Thread {
final ObjectTar objectTar;
Thread parkThread;
UnParkThread(String name, ObjectTar tar, Thread parkThread) {
super(name);
this.objectTar = tar;
this.parkThread = parkThread;
}
@Override
public void run() {
System.out.println(getName() + " Get the lock , It's done objectTar Of name initialization ");
objectTar.setName(" Braised chicken ");
// Be careful unpark A thread object was passed in
LockSupport.unpark(parkThread);
System.out.println(getName() + " After execution LockSupport.unpark() after , Continue to execute your business logic ");
}
}
1:ParkThread Get the lock , Prepare to execute your own business logic
2:ParkThread Find that the current situation can not meet their own requirements , Then perform LockSupport.park()
3:UnParkThread Get the lock , It's done objectTar Of name initialization
4:ParkThread from LockSupport.park() return , Complete your business logic , Braised chicken
5:UnParkThread After execution LockSupport.unpark() after , Continue to execute your business logic
Be careful 4、5 The order of is not necessarily , This and wait/notify It's different .
Knowledge point
- LockSupport.park(),park It means parking , Then this method is equivalent to thread “ Parking ” 了 , That's it “ Blocking ” Chant
- LockSupport.unpark(Thread thread),unpark That's it “ Don't stop ” 了 , Go away , Parameter has a thread , You can specify a specific thread from “ Blocking ” Let it go
and wait/notify The difference between
From the above example , We can see the difference below :
- LockSupport Realize the communication between threads , There is no need to resort to Object To achieve the goal
- LockSupport It can realize the specified thread from “ Blocking ” Release in state
- There is another point that is not shown in the example , That's it LockSupport There is no need to worry about the operation sequence of blocking and wakeup . What does that mean , That is to say, if our code is not executed first park To block threads , Then wait for another thread unpark To wake up the blocking thread , But first unpark, And then execute park, that park It won't block , It will then execute the subsequent business logic ; This and wait/notify It's different ,wait/notify There are strict sequence requirements for realizing thread blocking wakeup , Must first wait, Then you can notify. If first notify, So another thread wait Then it may block permanently 【 Of course, this situation is entering wait It won't appear when the business logic judgment is ok 】.
Principle analysis
park and unpark All are native Method , The bottom is C Realized . Let's put it simply :
- One per thread Park example , There is a field inside “volatile int _counter”, It's equal to 0 It means that you have not obtained “ voucher ”, Threads should be blocked . He is equal to 1 When , Indicates that the thread gets “ voucher ”, In other words, the lock mark is obtained in a quite traditional sense , You can also execute the following business logic .
- park Every time the method is executed , Will consume one “ voucher ”, amount to “_counter- - ”
- unpark If the method is executed continuously , And there is no park To consume “ voucher ” Words , Only one voucher will be generated . That is to say, regardless of unpark How many times , There is only one thread “ voucher ”.
summary
LockSupport yes JDK A communication tool used to realize thread blocking and wakeup in . Compared with wait/notify, It's more flexible , Independent of objects , You can specify any thread to wake up , And don't worry about the operation sequence of blocking and wakeup , But we need to pay attention , The effect of continuous multiple wakeups is the same as that of one wakeup .
JDK And the lock under the contract and other synchronization tools are widely used in the bottom layer LockSupport To realize the communication between threads , Mastering its principle and usage will help us better understand these JUC The underlying implementation is helpful .
边栏推荐
- Filters get the data in data; Filters use data in data
- IP地址分类,判断一个网段是子网超网
- Awk from getting started to digging in (20) awk parsing command line parameters
- 阿里云技术专家邓青琳:云上跨可用区容灾和异地多活最佳实践
- Software testing -- 1. Outline of software testing knowledge
- 【MySQL必知必会】触发器 | 权限管理
- 45padding won't open the box
- (original) customize a scrolling recyclerview
- 云安全技术发展综述
- LeetCode_ Factorization_ Simple_ 263. Ugly number
猜你喜欢

Development of uni app offline ID card identification plug-in based on paddleocr

Gameframework making games (II) making UI interface

Browser based split screen reading

51 single chip microcomputer learning notes (2)

Go语言创始人从Google离职

PS making and loading GIF pictures tutorial

IP address classification, which determines whether a network segment is a subnet supernetwork

As methods for viewing and excluding dependencies

基于AMD EPYC服务器的EDA芯片设计解决方案

变分(Calculus of variations)的概念及运算规则
随机推荐
[C topic] the penultimate node in the Niuke linked list
LeetCode-198-打家劫舍
[eloquence] negotiation persuasion skills and Strategies
转载----如何阅读代码?
D2. picking carrots (hard version) (one question per day)
Thymeleaf controls whether display is displayed through style
51单片机学习笔记(2)
[C题目]力扣206. 反转链表
LeetCode_因式分解_简单_263.丑数
PHP 通过原生CURL实现非阻塞(并发)请求模式
39 简洁版小米侧边栏练习
32 use of chrome debugging tools
awk从入门到入土(21)awk脚本调试
Realsense-Ros安装配置介绍与问题解决
27 选择器的分类
QObject源码剖析-d指针和q指针
Awk from entry to earth (24) extract the IP of the instruction network card
Number of high-quality number pairs [bit operation characteristics + abstract ability evaluation + grouping fast statistics]
Spark 参数配置的几种方法
Products on Apple's official website can save 600 yuan by buying iPhone 13 Pro max at a discount