当前位置:网站首页>[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 threadswait After being awakened , Will try again to get the lock , There will be competition in this processWake 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 ofOtherwise, an exception will be reportedcall wait() and notify() The object of must be the same object To wait and wake upMore 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 problemWhen 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
边栏推荐
- In the Alibaba cloud experiment, if the k8s forwards to port 3306 and the MySQL client is turned on, it will terminate abnormally. What is the reason?
- Etcd可视化工具:Kstone部署(一),基于Helm快速部署
- Logstash excludes specific files or folders from collecting report log data
- Weekly snapshot of substrate technology 20220411
- 【Pygame小游戏】这款“吃掉一切”游戏简直奇葩了?通通都吃掉嘛?(附源码免费领)
- After the mobile phone, it was reported that Samsung also cut the output of TV and other home appliance product lines
- 数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】
- Oracle概念二
- 阿里云刘珅孜:云游戏带来的启发——端上创新
- The two trump brand products of Langjiu are resonating in Chengdu, continuously driving the consumption wave of bottled liquor
猜你喜欢

【多线程】线程通信调度、等待集 wait() 、notify()

EMQ 助力青岛研博建设智慧水务平台

LeetCode每日一练(无重复字符的最长子串)
![[pygame Games] ce jeu](/img/3c/e573106ec91441a554cba18d5b2253.png)
[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)

带你认识图数据库性能和场景测试利器LDBC SNB

Four characteristics of transactions

米哈游起诉五矿信托,后者曾被曝产品暴雷

LeetCode每日一练(两数之和)

Open source 23 things shardingsphere and database mesh have to say
Yyds dry inventory brief chrome V8 engine garbage collection
随机推荐
C language course design
After the mobile phone, it was reported that Samsung also cut the output of TV and other home appliance product lines
Redis Series 2: data persistence improves availability
National food safety risk assessment center: do not blindly and unilaterally pursue "zero addition" and "pure natural" food
3.1 simple condition judgment
2/15 topology sorting +dfs (the order of specified directions is very important) +bfs
logstash排除特定文件或文件夹不采集上报日志数据
Oracle概念三
Does polardb-x open source support mysql5.7?
10分钟掌握mysql的安装步骤
开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事
P. Simple application of a.r.a method in Siyuan (friendly testing)
Detailed explanation of various GPIO input and output modes (push-pull, open drain, quasi bidirectional port)
Mobile terminal click penetration
一个机器人位于一个 m x n 网格的左上角 。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角。问总共有多少条不同的路径?【LeetCodeHot100】
锚文本大量丢失的问题
Source NAT address translation and server mapping web page configuration of firewall Foundation
数据中心表格报表实现定制统计加班请假汇总记录分享
【Pygame小遊戲】這款“吃掉一切”遊戲簡直奇葩了?通通都吃掉嘛?(附源碼免費領)
数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】