当前位置:网站首页>"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 .
边栏推荐
- 45padding won't open the box
- 基于AMD EPYC服务器的EDA芯片设计解决方案
- Practical guide for network security emergency response technology (Qianxin)
- Login of MySQL [database system]
- Thymeleaf controls whether display is displayed through style
- 41 图片背景综合-五彩导航图
- [nuxt 3] (XI) transmission & module
- 【MySQL必知必会】触发器 | 权限管理
- GameFramework制作游戏(二)制作UI界面
- Go语言创始人从Google离职
猜你喜欢
![[MySQL must know and know] trigger | permission management](/img/59/cb805d972097a6a8ed7f3ae454a91d.png)
[MySQL must know and know] trigger | permission management

Idea error failed to determine a suitable driver class

32 use of chrome debugging tools

Alibaba cloud installs mysql5.7

Products on Apple's official website can save 600 yuan by buying iPhone 13 Pro max at a discount

L1 and L2 regularization

变分(Calculus of variations)的概念及运算规则

06. Neural network like

Melody + realsense d435i configuration and error resolution

44 Sina navigation, Xiaomi sidebar exercise
随机推荐
SQL优化的一些建议,希望可以帮到和我一样被SQL折磨的你
Polymorphism and interface
[nuxt 3] (XI) transmission & module
Yes, UDP protocol can also be used to request DNS server
Dpkg package download addresses of various platforms (including arm64)
Gameframework making games (II) making UI interface
关于ROS2安装connext RMW的进度条卡在13%问题的解决办法
关于RDBMS和非RDBMS【数据库系统】
Awk from entry to earth (24) extract the IP of the instruction network card
Copy files / folders through Robocopy
Paddlenlp's UIE relationship extraction model [executive relationship extraction as an example]
Educational codeforces round 132 (rated for Div. 2) C, d+ac automata
I2C device driver hierarchy
Gameframework making games (I)
32 use of chrome debugging tools
物理量与单位符号的书写标准
H5页面input输入框弹起数字键盘,需要支持小数点
L1 and L2 regularization
Spark 参数配置的几种方法
kibana操作es