在指定毫秒數內,讓正在執行的當前線程進入休眠期。ide
public class SleepDemo extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis()); } public static void main(String[] args) { SleepDemo demo = new SleepDemo(); demo.setName("demo"); demo.start(); try { System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis()); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
運行結果以下:
結果能夠看出,main線程的兩次時間相差1000毫秒,demo的兩次時間相差2000毫秒,sleep隻影響本身的線程運行,不影響其餘線程。spa