当前位置:网站首页>[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
边栏推荐
- Yyds dry inventory brief chrome V8 engine garbage collection
- National food safety risk assessment center: do not blindly and unilaterally pursue "zero addition" and "pure natural" food
- 华为云DevCloud重磅发布四大新能力,创下国内两项第一
- What should the ultimate LAN transmission experience be like
- Construction and management practice of ByteDance buried point data flow
- What is RPC
- 域名绑定动态IP最佳实践
- 开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事
- Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
- localDateTime类型的时间(2019-11-19T15:16:17) 用oracle的时间范围查询
猜你喜欢

Raspberry pie preliminary use

Sliding window + monotone queue concept and example (p1886 Logu)

Kubernetes基础自学系列 | Ingress API讲解

A distribution fission activity is more than just a circle of friends!

Smart wind power | Tupu software digital twin wind turbine equipment, 3D visual intelligent operation and maintenance

Mihayou sued Minmetals trust, which was exposed to product thunderstorms

开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事

LeetCode每日一练(无重复字符的最长子串)

Bit.Store:熊市漫漫,稳定Staking产品或成主旋律

3.3 one of the fixed number of cycles
随机推荐
Hung - Mung! HDD Hangzhou station · salon hors ligne vous invite à construire l'écologie
If you want to use DMS to handle database permissions, can you only use Alibaba cloud ram accounts (Alibaba cloud RDS)
Leetcode daily practice (Yanghui triangle)
After the mobile phone, it was reported that Samsung also cut the output of TV and other home appliance product lines
C语言教师工作量管理系统
当发布/订阅模式遇上.NET
郎酒两大王牌产品成都联动共振,持续带动光瓶酒消费浪潮
Oracle概念三
Handling of difficult and miscellaneous problems during the installation and configuration of qt5.5.1 desktop version (configuring arm compilation Kit)
关于VS2019C#如何建立登陆界面输入的用户名和密码需与Access数据库的记录相匹配
正则匹配以什么开头、以什么结尾,以非什么开头,以非什么结尾
QT5.5.1桌面版安装配置过程中的疑难杂症处理(配置ARM编译套件)
2/15 topology sorting +dfs (the order of specified directions is very important) +bfs
The time of localdatetime type (2019-11-19t15:16:17) is queried with the time range of Oracle
华为云首次解读云原生2.0十大典型架构,加速构建现代化应用
National food safety risk assessment center: do not blindly and unilaterally pursue "zero addition" and "pure natural" food
鸿蒙发力!HDD杭州站·线下沙龙邀您共建生态
继手机之后 报道称三星也削减了电视等家电产品线的产量
【牛客刷题】NowCoder号称自己已经记住了1-100000之间所有的斐波那契数。 为了考验他,我们随便出一个数n,让他说出第n个斐波那契数。如果第n个斐波那契大于6位则只取后6位。
List转Table