Home >Java >javaTutorial >What is the usage of sleep in java
The usage of sleep in java is: force the currently executing thread to sleep (pause execution), for example: [Thread.sleep(long millis)] When the thread sleeps, it will not return to runnable before waking up. state; it will return to the runnable state after the sleep time expires.
The usage of sleep in java is:
Thread.sleep(long millis)
and Thread.sleep(long millis, int nanos)
static method forces the currently executing thread to sleep (pause execution) to "slow down the thread".
When a thread sleeps, it sleeps somewhere and does not return to a runnable state until it wakes up.
When the sleep time expires, it returns to the runnable state.
1. Reasons for thread sleep: The thread executes too fast, or needs to be forced to enter the next round, because the Java specification does not guarantee reasonable rotation.
2. Implementation of sleep: Call static method.
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
3. Sleeping position: In order to give other threads a chance to execute, you can put the call to Thread.sleep()
on the thread Within run()
. This ensures that the thread will 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); //暂停,每一秒输出一次 }catch (InterruptedException e) { return; } } } }
Note:
1. Thread sleep is the best way to help all threads get a chance to run.
2. The thread automatically wakes up after its sleep expires and returns to the runnable state, not the running state. The time specified in sleep() is the minimum time that the thread will not run. Therefore, the sleep() method cannot guarantee that the thread will start executing after its sleep expires.
3. sleep() is a static method and can only control the currently running thread.
Example: a counter that counts to 100, pauses for 1 second between each number, and outputs a string every 10 numbers
public class MyThread 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(1000); System.out.print(" 线程睡眠1秒!\n"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { new MyThread().start(); } }
Recommended tutorial: "java video tutorial"
The above is the detailed content of What is the usage of sleep in java. For more information, please follow other related articles on the PHP Chinese website!