当前位置:网站首页>[multithreading] thread communication scheduling, waiting set wait(), notify()
[multithreading] thread communication scheduling, waiting set wait(), notify()
2022-06-27 16:39:00 【51CTO】
Catalog
Object waiting set to interfere with thread scheduling
wait and notify In order to deal with the randomness of thread scheduling .
Or that sentence , Multithreaded scheduling , Because of its randomness , It leads to the code who executes first , Who's going to do it later , There are too many variables .
And we programmers don't like randomness , We like certain things .
Need to be able to get threads to each other , There is a fixed order .
for instance : To play basketball
There is a typical operation in basketball : Pass the ball , Layup .
Then we must pass the ball first , Lay up again . It requires the cooperation of two team members .
Two players are two threads .
If it's a layup first , But the ball didn't reach , Also on a lonely .
Generally, the most stable method , They pass the ball first and then lay up .
In this order , It is also very necessary in our actual development .
Therefore, we need to have means to control !
As mentioned before join It is also a way of sequential control , however join Prefer to control the end of the thread
. therefore join There are limitations in use .
It's not like wait and notify More suitable for use .
wait Method
Actually wait() The method is to stop the thread .
Method wait() Its function is to make the current thread executing code wait
,wait( ) The method is Object Class method , This method is used to put the current thread into “ Pre execution queue ” in , And in wait() Stop execution at code , Until notified or interrupted .wait( ) Method can only be invoked in synchronous or synchronous blocks. . If the wait() when , Not holding the proper lock , It throws an exception
.- wait( ) After method execution , The current thread releases the lock , And has been waiting for notification , Until other threads wake up the thread and compete with other threads to re acquire the lock .
call wait Method thread , It's going to get stuck , Blocked until another thread passes notify To inform .
notify Method
A thread executes to object.wait() Then I waited , Then the program can't wait like this . At this time, you need to use another method to wake up notify().
notify The method is to make the stopped thread continue to run
Method notify() It is also invoked in synchronous or synchronous blocks
, This method is used to notify other threads that may be waiting for the object lock of the object , Give notice to notify, And make them regain the object lock of the object .If there are multiple threads waiting , Then a thread planner randomly selects one wait Thread in state .
- stay notify() After the method , The current thread will not release the object lock immediately , Wait until the execution notify() Method to finish executing the program , That is, the object lock will not be released until the synchronization code block is exited .
According to this mechanism, we can arrange the sequence of multiple threads
notifyAll Method
As mentioned above wait and notify All operate on the same object .
for example :
Now there is
An object o
, By 10 A thread calledo.wait
.
here10 individual Threads are blocked
.
If calledo.notify
, It will10 One of the threads wakes up
【 Random wake up : Not sure which thread will be awakened next 】
The awakened thread will continue to execute . Other threads are still blocked .
If
Called o.notifyAll
, willWake up all threads
wait After being awakened , Will try again to get the lock , There will be competition in this process
Wake up all threads , Grab the lock .
I got it , Then we can carry on .
Failed threads , Continue to wait for , Waiting for the next notifyAll.**
wait Methods to summarize
wait( )
The role of isPut the current thread into a waiting state
, meanwhile ,wait( ) It also causes the current thread to release the lock it holds .
Until another thread calls the notify() Method or notifyAll() Method , Wake up the current thread ( Get into “ Ready state ”)
- notify() and notifyAll() The role of , Wake up the waiting thread on the current object
notify() Is to wake up a single thread
notifyAll() Is to wake up all threads
, Then these threads compete for the same lock .( Not recommended notifyAll )
wait(long timeout) Leave the current thread in “ wait for ( Blocking ) state
”
“ until Other threads call the... Of this object notify() Method or notifyAll() Method
perhaps Over a specified amount of time ”, The current thread is awakened ( Get into “ Ready state ”)
summary :
wait() The working process of is :
Release object lock ( So there must be a lock to execute normally )
Wait for a notice
( It may take a long time , Because they don't participate in the competition of subsequent locks Until another thread calls the object's notify() To wake up the thread )After receiving the notice Try to reacquire the object lock So let's keep going
Particular attention
wait() and notify() The operation must be placed in synchronized Within the code block of
Otherwise, an exception will be reportedcall wait() and notify() The object of must be the same object To wait and wake up
More precisely : because wait and notify To be in synchronized Within the code block So the locked object should also be the same as wait() and notify() The object of must be the same object This is the 4 Objects must be consistent
notify Methods to summarize
- A thread executes to object.wait() Then I waited , Then the program can't wait like this . At this time, you need to use another method to wake up notify().
- notify The method is to make the stopped thread continue to run .
- Method notify() It is also invoked in synchronous or synchronous blocks , This method is used to notify other threads that may be waiting for the object lock of the object , Give notice to notify, And make them regain the object lock of the object . If there are multiple threads waiting , Then a thread planner randomly selects one wait Thread in state .
- stay notify() After the method , The current thread will not release the object lock immediately , Wait until the execution notify() Method to finish executing the program , That is, the object lock will not be released until the synchronization code block is exited .
Be careful :
Wake up the thread not too early , If there is no thread waiting , Premature wakeup of threads , At this time, there will be wake-up first , Waiting for the effect .
such There is no need to run wait The method . Leading to race condition problems
Running results :
Race condition problem
Race condition problem
When one t The thread executes wait() Method releases the object lock Another one t1 The thread acquires the lock and immediately executes notify() Method area notification t Threads however t The thread has not yet executed the code waiting for notification So the notice was missed This thread t It's going to wait This is a race condition problem- In order to solve and
Avoid this problem In fact, when we are executing wait() During operation Releasing the lock and waiting for the notification to be received are performed in an atomic nature Finally, try to re acquire the lock
wait And sleep Comparison of
- wait For communication between threads sleep Used to block threads for a period of time
- wait There must be a lock before wait Then the lock will be released Try to request the lock again after being awakened
- sleep It ignores the existence of locks I.e. no lock is required And will not release the lock
- wait yes object Methods
- sleep yes thread Static method of
- The only thing in common is that you can let the thread give up execution for a period of time
边栏推荐
- 继手机之后 报道称三星也削减了电视等家电产品线的产量
- Pragma once Usage Summary
- 事务的四大特性
- 等保2.0密码要求是什么?法律依据有哪些?
- 【Pygame小遊戲】這款“吃掉一切”遊戲簡直奇葩了?通通都吃掉嘛?(附源碼免費領)
- Bit. Store: long bear market, stable stacking products may become the main theme
- 泰山OFFICE技术讲座:第一难点是竖向定位
- Deeply digitise, lead cloud nativity and serve more developers
- Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
- The time of localdatetime type (2019-11-19t15:16:17) is queried with the time range of Oracle
猜你喜欢
List转Table
郎酒两大王牌产品成都联动共振,持续带动光瓶酒消费浪潮
Sliding window + monotone queue concept and example (p1886 Logu)
Etcd visualization tool: kstone deployment (I), rapid deployment based on Helm
数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】
Practice of constructing ten billion relationship knowledge map based on Nebula graph
IDE Eval reset unlimited trial reset
Yyds dry inventory brief chrome V8 engine garbage collection
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
Yyds dry inventory solution sword finger offer: a path with a certain value in the binary tree (3)
随机推荐
Event listening mechanism
锚文本大量丢失的问题
About how vs2019c # establishes the login interface, the user name and password entered must match the records in the access database
What should the ultimate LAN transmission experience be like
C language course design
【牛客刷题】NowCoder号称自己已经记住了1-100000之间所有的斐波那契数。 为了考验他,我们随便出一个数n,让他说出第n个斐波那契数。如果第n个斐波那契大于6位则只取后6位。
特殊函数计算器
等保2.0密码要求是什么?法律依据有哪些?
ICML 2022 ぷ the latest fedformer of the Dharma Institute of Afghanistan ⻓ surpasses SOTA in the whole process of time series prediction
Source NAT address translation and server mapping web page configuration of firewall Foundation
Weekly snapshot of substrate technology 20220411
SQL parsing practice of Pisa proxy
Yyds dry inventory brief chrome V8 engine garbage collection
# Cesium实现卫星在轨绕行
【Pygame小游戏】这款“吃掉一切”游戏简直奇葩了?通通都吃掉嘛?(附源码免费领)
Open source 23 things shardingsphere and database mesh have to say
Deeply digitise, lead cloud nativity and serve more developers
国家食品安全风险评估中心:不要盲目片面追捧标签为“零添加”“纯天然”食品
#yyds干货盘点# 解决剑指offer:二叉树中和为某一值的路径(三)
数据中心表格报表实现定制统计加班请假汇总记录分享