Java. lang. ThreadOfSleep ()Method to pause the current thread for a period of time (unit: milliseconds ). Note that the parameters of the sleep () method cannot be negative. Otherwise, an IllegalArgumentException exception is thrown.
In addition, there is another method.Sleep (long millis, int nanos)This method can be used to pause the current thread in millis millisecond nanos nanoseconds. Note that the value range of the parameter nanos is [0, 999999].
The following code demonstrates how to useThread. sleep ()Method to suspend the main thread for 2 seconds.
ThreadSleep. java
package com.journaldev.threads;public class ThreadSleep { public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms = " + (System.currentTimeMillis()-start)); }}
If you run the above program, you will find that the final output result is slightly more than 2000, depending on how the thread sleep is implemented and the thread scheduling mechanism defined by the operating system.
Key Points of thread sleep
1. The current thread is always suspended when the thread sleep
2. Before being awakened and executed, the actual time for thread sleep depends on the system timer and scheduler. For idle systems, the actual sleep time is very close to the specified sleep time, but for busy systems, the gap between the two is large.
3. The thread sleep does not lose any monitors and locks that the current thread has acquired.
4. other threads can interrupt the sleep of the current process, but will throw an InterruptedException exception.
Working principle of thread sleep
Thread. sleep () interacts with the Thread scheduler, which sets the current Thread to a waiting state for a period of time. Once the wait time ends, the thread status will be changed to runnable, and the subsequent tasks will be started waiting for the CPU to execute. Therefore, the actual sleep time of the current thread depends on the thread scheduler, which is managed by the operating system.
Original article address: Java Thread Sleep Example