Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between sleep, yield, wait and join in java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the difference between sleep, yield, wait and join in java". The content in the article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the difference between sleep, yield, wait and join in java".

Overall summary:

1. Both Thread.sleep (long) and Thread.yield () are static methods of the Thread class, and both are called in the way of Thread.sleep (long) / Thread.yield () when called.

Join () is called by the thread object.

2.wait () and notify (), notifyAll () are all java.lang.Object methods!

Object is java.lang.Object, because it is said every day that Java is object-oriented, so Object is a superclass of all Java objects and implements Object methods.

They are all used to coordinate multiple threads' access to shared data, so these three methods must be used within the Synchronized statement block. As mentioned earlier, the keyword Synchronized is used to protect shared data and prevent other threads from accessing it. But the flow of the program is very inflexible. How can we give other threads a chance to access the shared data before the current thread exits the Synchronized data block? At this point, we use these three methods to control flexibly.

The wait () method pauses execution of the current thread and releases the object lock flag so that other threads can enter the Synchronized data block, and the current thread is placed in the object wait pool.

When the notify () method is called, an arbitrary thread is removed from the object's waiting pool and placed in the lock flag waiting pool. Only the thread in the lock flag waiting pool can acquire the lock flag; if there are no threads in the lock flag waiting pool, notify () does not work.

NotifyAll () removes all threads waiting for that object from the object waiting pool and places them in the lock flag waiting pool.

The difference between sleep and Wait:

Look at the difference, mainly look at the operating mechanism of CPU:

The difference between them mainly considers two points: whether the 1.cpu will continue to execute, and 2. Whether the lock is released.

For these two points, first explain the meaning of whether cpu continues to execute: cpu divides time slices for each thread to execute, each time slice is very short, and cpu keeps switching between different threads, as if they were executing at the same time.

Second, explain the meaning of whether the lock is released: if the lock is occupied, then this snippet of execution code is executed synchronously, and if the lock is released, other threads are allowed to continue to execute the block of code.

Knowing the meaning of the above two points, start analyzing sleep and wait:

After a period of sleep, the thread usually executes immediately, so you can see that cpu has been allocating time slices for this thread. If there is a Synchronize in the outer package, then the lock is not released. So sleep cpu continues to execute, and the lock is not released.

Wait, commonly used in locking mechanisms

(wait is used for the lock mechanism, sleep is not, which is why sleep does not release the lock, wait releases the lock, sleep is the thread's method, has nothing to do with the lock, and wait,notify,notifyall is used together for the lock mechanism)

The lock must be released, because notify will not immediately call up the thread, so cpu will not allocate a time slice to it, which means that the wait thread enters the waiting pool, cpu gives it no time slice, and the lock is released.

Description:

The method of the 1.sleep:Thread class must take a time parameter. It will let the current thread hibernate into blocking state and release CPU (Sleep releases CPU,wait), providing opportunities for other threads to run regardless of priority, but if there is a synchronization lock, sleep will not release the lock, that is, other threads cannot obtain the synchronization lock.

2.yield: give up CPU scheduling, methods of the Thread class, like sleep, but cannot be paused by the user for how long, and the yield () method can only give threads of the same priority a chance to execute. Yield () simply returns the current thread to an executable state, so the thread that executes yield () may be executed as soon as it enters the executable state. Calling the yield method is just a suggestion to tell the thread scheduler that I am done enough to allow other threads of the same priority to use CPU, and there is no mechanism to guarantee adoption.

The methods of the 3.wait:Object class (notify (), notifyAll () are also Object objects) must be placed in the loop body and the synchronization code block. The thread executing the method releases the lock and enters the thread waiting pool to be awakened again (notify wakes up randomly, notifyAll all wakes up, thread ends automatically wakes up), that is, it is put into the lock pool to compete for synchronization locks.

4.join: a special wait in which the current running thread invokes the join method of another thread, and the current thread enters a blocking state until the other thread ends and waits for that thread to terminate. Note that this method also needs to catch exceptions.

Wait for the thread calling the join method to finish before continuing execution. For example, t.join (); / / is mainly used to wait for t thread to finish running. Without this sentence, main will finish execution, resulting in unpredictable results.

Comparison of several methods

Thread.sleep (long millis), which must be the current thread calling this method, the current thread enters blocking, but does not release the object lock, and the thread automatically wakes up to the runnable state after millis. Purpose: the best way to give other threads a chance to execute.

Thread.yield (), which must be the current thread calling this method, the current thread abandons the acquired cpu time slice and changes from the running state to the runnable state, allowing OS to select the thread again. Purpose: let threads of the same priority take turns, but there is no guarantee that they will take turns. In practice, there is no guarantee that yield () will achieve the purpose of concession, because the concessionary thread may be selected again by the thread scheduler. Thread.yield () does not cause blocking.

T.join () / t.join (long millis), the current thread calls the join method of other thread 1, the current thread blocks, but does not release the object lock, until thread 1 finishes execution or the millis time is up, the current thread enters the runnable state.

Obj.wait (), the current thread calls the object's wait () method, and the current thread releases the object lock and enters the waiting queue. Rely on notify () / notifyAll () wake up or wait (long timeout) timeout time to wake up automatically.

Obj.notify () wakes up a single thread waiting on this object monitor, and the choice is arbitrary. NotifyAll () wakes up all threads waiting on this object monitor.

Show codes timeimport lombok.extern.slf4j.Slf4j;import java.util.Random;/** * implement online * @ author wucj * @ date 2019-06-30 16:40 * * / @ Slf4jpublic class ThreadAStatus implements Runnable {private String name; private volatile int count; public ThreadAStatus (String name) {this.name = name;} @ Override public void run () {log.info ("Thread {}, execution times: {}", name,++count) Try {log.info ("Thread {} starts execution, current {} times", name,count); int maxCount = 10; for (int item0witi

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report