1. Sleep () Introduction
Sleep () is defined in Thread.java.
The function of sleep () is to let the current thread hibernate, that is, the current thread goes from "Running state" to "hibernate (blocked) state". Sleep () Specifies the sleep time at which the thread sleeps longer than/equal to the sleep time, and when it is woken up, it is changed from "blocked state" to "ready state", thus waiting for the CPU to schedule execution.
2. Sleep () example
The use of sleep () is shown below through a simple example.
1//Sleeptest.java Source 2 class Threada extends thread{3 public threada (String name) {4 Super (n AME); 5} 6 Public synchronized void Run () {7 try {8 for (int i=0; I <10; i++) {9 System.out.printf ("%s:%d\n", This.getname (), i); Ten//I can be divisible by 4, sleep 100 milliseconds each if (i%4 = = 0) thread.sleep (100); 13 } The catch (Interruptedexception e) {e.printstacktrace ();}17} publi C class sleeptest{public static void Main (string[] args) {Threada T1 = new Threada ("T1"); . Start (); The
Operation result :
T1:0t1:1t1:2t1:3t1:4t1:5t1:6t1:7t1:8t1:9
Result Description :
The program is relatively simple and starts thread T1 in main thread main. After the T1 is started, T1 will sleep 100 milliseconds through Thread.Sleep (100) when calculation I in T1 is divisible by 4.
3. Comparison of sleep () and wait ()
We know that the role of Wait () is to allow the current thread to enter the "waiting (blocking) state" by the "Running state" and also release the Sync lock. The function of sleep () is to let the current thread go into hibernation (blocked) state by the "Running state".
However, wait () frees the object's sync lock, and sleep () does not release the lock.
1//Sleeplocktest.java Source 2 public class sleeplocktest{3 4 private static Object obj = new Object (); 5 6 Pub Lic static void Main (string[] args) {7 Threada t1 = new Threada ("T1"); 8 Threada t2 = new Threada ("T2"); 9 T1.start (); Ten T2.start (); one}, static class Threada extends Thread{14 public Threada (String name) {15 Super (name); () \ 18///Get the synchronization lock for obj object (obj) {20 try {(int i=0; I <10; i++) {System.out.printf ("%s:%d\n", this . GetName (), i); When I can be divisible by 4, sleep 100 milliseconds if (i%4 = = 0) Thread . Sleep (+),}27} catch (Interruptedexception e) {E.printsta Cktrace (); 29}30}31} 32} 33}
Operation result :
T1:0t1:1t1:2t1:3t1:4t1:5t1:6t1:7t1:8t1:9t2:0t2:1t2:2t2:3t2:4t2:5t2:6t2:7t2:8t2:9
Result Description :
The main thread, main thread, starts with two threads T1 and t2. T1 and T2 in run () refer to the synchronization lock of the same object, that is, synchronized (obj). While the T1 is running, it calls Thread.Sleep (100), but T2 does not get CPU execution. Because, T1 did not release "the synchronization lock held by obj"!
Note that if we comment out synchronized (obj) and execute the program again, T1 and T2 can switch to each other.
Java multithreading--thread hibernation