The Thread sleep methods are Thread. sleep (long millis) and Thread. sleep (long millis, int nanos)
Sleep () is measured in milliseconds.
Question 1: Which thread will sleep during sleep
Answer: which thread calls sleep and which will sleep
Problem 2. The main thread can sleep
Yes
Thread. sleep () is often called to wait for the program. For example, if you want your program to be periodically executed, you can write a code
| The code is as follows: |
Copy code |
Int a = 2
While (a> 1 ){
Run...
Thread. sleep (24*3600*1000); // run once a day
}
|
Let's look at an example.
| The code is as follows: |
Copy code |
|
Package com. javaer. thread;
Public class TSleep implements Runnable {
Public static void main (String [] args ){
Thread s1 = new Thread (new TSleep (), "S1 ");
Thread s2 = new Thread (new TSleep (), "S2 ");
S1.start ();
S2.start ();
}
@ Override
Public void run (){
// TODO Auto-generated method stub
For (int I = 0; I <10; I ++ ){
System. out. println ("Thread" + Thread. currentThread (). getName () + "" + I + "times! ");
Try {
Thread. sleep (30 );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
} |
Thread S1 0th executions!
Thread S2 0th executions!
Thread S1 1st Executions!
Thread S2 1st Executions!
Thread S1 2nd executions!
Thread S2 2nd executions!
Thread S2 3rd executions!
Thread S1 3rd executions!
Thread S1 4th executions!
Thread S2 4th executions!
Thread S1 5th executions!
Thread S2 5th executions!
Thread S2 6th executions!
Thread S1 6th executions!
Thread S1 7th executions!
Thread S2 7th executions!
Thread S2 8th executions!
Thread S1 8th executions!
Thread S1 9th executions!
Thread S2 9th executions!
The example shows that the time sleep of a thread is not precisely controlled, but close to precision. Sometimes thread s2 is executed first.