当前位置:网站首页>Wait (), notify (), notifyAll (), sleep (), condition, await (), signal()

Wait (), notify (), notifyAll (), sleep (), condition, await (), signal()

2022-06-25 11:20:00 User 9854323

wait()、notify() and notifyAll() yes Object class The method in From the text description of these three methods, we can know the following information : 1) wait()、notify() and notifyAll() Methods are local methods , And for final Method , Can't be rewritten . 2) Call... Of an object wait() Method to block the current thread , And the current thread must own this object monitor( Immediate lock ) 3) Call... Of an object notify() Method can wake up a waiting object monitor The thread of , If there are multiple threads waiting for this object monitor, You can only wake up one of the threads ; 4) call notifyAll() Method can wake up all waiting for this object monitor The thread of ; 5 ) If you call the wait() Method , The current thread must have the monitor( Immediate lock ), So call wait() Method must be in synchronization block or synchronization method (synchronized Block or synchronized Method ). 6 ) Call... Of an object wait() Method , Equivalent to having the current thread hand over the object monitor, Then enter the waiting state , Wait for the lock of this object to be acquired again later (Thread Class sleep The thread pauses the execution of the method for a period of time , This gives other threads a chance to continue , But it doesn't release the object lock ); 7 ) Call... Of an object notify() Method , The current thread must also own this object monitor, So call notify() Method must be in synchronization block or synchronization method (synchronized Block or synchronized Method ).

Condition Is in java 1.5 It's not until now , It's used to replace the traditional Object Of wait()、notify() Realize the cooperation between threads , Compared with Object Of wait()、notify(), Use Condition Of await()、signal() It is safer and more efficient to realize the cooperation between threads in this way . Therefore, it is generally recommended to use Condition.

1 ) Condition It's an interface , The basic method is await() and signal() Method ; 2 ) Condition Depend on Lock Interface , Generate a Condition The basic code is lock.newCondition() 3 ) call Condition Of await() and signal() Method , Must be in lock Within protection , That is to say, it must be lock.lock() and lock.unlock Can only be used between

Conditon Medium await() Corresponding Object Of wait(); Condition Medium signal() Corresponding Object Of notify(); Condition Medium signalAll() Corresponding Object Of notifyAll()

原网站

版权声明
本文为[User 9854323]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251056180072.html