Java thread sleep (), wait (), yield () three methods of the role and characteristics, sleepyield
--- Restore content start ---
Sleep: The thread is sleep, so that the thread in the direct row is paused for a period of time and enters the timed wait state.
Method: After static void sleep (long millis) calls sleep, the current thread gives up the CPU. during the specified period, the thread where sleep is located will not receive execution opportunities. The thread in this status does not release the synchronization lock/synchronization listener.
This method is more used to simulate network latency, so that multiple threads can access the same resource concurrently.
Wait, thread communication method, java. lang. Object class provides two types of methods used to operate thread communication.
Wait (): The thread object that executes this method releases the synchronization lock. JVM stores this thread in the waiting pool and waits for other threads to wake up the thread.
Y (): the thread that executes this method wakes up any thread waiting in the waiting pool and forwards the thread to the lock pool for waiting.
Yyall (): the thread that executes this method wakes up all the threads waiting in the waiting pool and forwards the threads to the lock pool for waiting.
(Note: The above method can only be called by synchronous listening lock objects; otherwise, the error "IllegalMonitorStateException" is returned .)
Yield indicates that the current thread object prompts the scheduler to give up the CPU, but the scheduler can ignore the prompt freely.
After this method is called, the thread object enters the ready state, so it is entirely possible that after a thread calls yield (), the thread scheduler schedules it and re-executes it.
The document provided by Java 7 clearly shows that this method is rarely used in development. This method is mainly used for debugging or testing, it may be helpful for re-occurrence of errors due to multi-thread competition.
In addition, the sleep method and yield method are different:
1. The current running thread can discard the CPU and give the running opportunity to other threads.
2. The sleep method gives other threads a running opportunity, but does not consider the priority of other threads. The yield method only gives the thread running opportunity with the same or higher priority.
3. After the sleep method is called, the thread enters the timer wait state. After the yield method is called, the thread enters the ready state.
Thread declaration cycle diagram: