Thread. Sleep (long millis) and thread. Sleep (long millis, int Nanos) Static Methods force the currently executing thread to sleep (pause execution) to "slow down the thread ".
When a thread is sleeping, it sleeps somewhere and does not return to a running state before waking up.
When the sleep time expires, the system returns to the running status.
Cause of thread sleep: the thread runs too fast or needs to be forced to enter the next round, because the Java specification does not guarantee reasonable rotation.
Implementation of sleep: Call static methods.
try { Thread.sleep(1000)
} catch (InterruptedException e) { e.printStackTrace();}
Sleep location: in order to give other threads the opportunity to execute, you can put the call of thread. Sleep () within the thread run. In this way, the thread will be sleep during execution.
Public class testsleep {public static void main (string [] ARGs) {mythread2 T1 = new mythread2 ("testsleep"); t1.start (); For (INT I = 0; I <10; I ++) system. out. println ("I am main thread") ;}} class mythread2 extends thread {mythread2 (string s) {super (s) ;} public void run () {for (INT I = 1; I <= 10; I ++) {system. out. println ("I am" + getname (); try {sleep (1000); // pause, output once every second} catch (interruptedexception e) {return ;}}}}
Note:
1. Thread sleep is the best way to help all threads get running opportunities.
2. The thread automatically wakes up after its sleep ends and returns to the running status, not the running status. The time specified in sleep () is the shortest time that the thread does not run. Therefore, the sleep () method cannot guarantee that the thread starts to run after its sleep expires.
3. Sleep () is a static method and can only control the currently running threads.
Example 2: one counter, counting to 100, paused for 1 second between each number, and output a string every 10 digits
Public class testsleep extends thread {public void run () {for (INT I = 0; I <100; I ++) {If (I) % 10 = 0) {system. out. println ("-------" + I);} system. out. print (I); try {thread. sleep (1, 1000); system. out. print ("thread sleep for 1 second! \ N ");} catch (interruptedexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {New testsleep (). start ();}}
References: http://blog.sina.com.cn/s/blog_5c5bc9070100ytxz.html