sleep (thread), join (), yield () method What is the difference?

sleep (), join (), yield () What is the difference?

sleep()

sleep () method to specify the time to wait, it allows the currently executing thread is suspended within the specified time to perform, enter the blocked state, the method can not only make other same priority or high priority threads get a chance to execute, but also it allows low-priority thread gets the opportunity to perform. But the sleep () method does not release the "lock flag", meaning that if there are synchronized sync block other threads still can not access the shared data.

wait()

wait () method needs and notify () and notifyAll () describes two methods together, these three methods for coordinating multiple threads to access shared data, it must be used within a synchronized statement block, i.e., call wait (), notify () and notifyAll () task must have a lock object before calling these methods.

Note that they are the Object class method instead of the Thread class method.

wait () method is different from the sleep () method is that, wait () method releases the "lock flag" object. When you call an object's wait () method, the current thread will be suspended, and the current thread into the wait pool object is, until you call the notify () method, the object is removed from any waiting pool and a thread into the lock flag wait in the pool, only lock flag wait pool thread can acquire the lock symbol, which is ready to compete for ownership of the lock. When an object is called notifyAll () method, the object will wait for all threads in the pool are moved to the object lock flag waiting pool.

Except notify () and notifyAll () method can also be used with millisecond wait parameter (Long timeout) method, the effect is the delay timeout milliseconds, the suspended thread lock flag is restored to the waiting pool.

In addition, wait (), notify () and notifyAll () can only be used in synchronized statement, but if you are using ReenTrantLock synchronization, how to achieve the effect of these three methods do? The solution is used by ReentrantLock.newCondition () Gets a Condition class object, then the Condition await (), signal () and signalAll () respectively corresponding to the above three methods.

yield()

Similar yield () method, and sleep () method, it will not release the "lock flag" except that it has no parameters, namely the yield () method simply makes the current thread back to the executable state, execution yield () thread there may be executed immediately after entering the state to perform additional yield () method can only be the same priority or high priority thread gets the opportunity to perform, this is also sleep () method different.

join()

join () method after the end of the current thread will wait for call join () method thread to continue execution

Guess you like

Origin www.cnblogs.com/zxfei/p/11080090.html