sleep
在指定毫秒数内,让正在执行的当前线程进入休眠期。
示例
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只影响自己的线程运行,不影响其他线程。