線程的sleep方法簽名位:
public static void sleep(long millis) throws InterruptException, 是靜態方法,使目前正在執行的線程休眠millis毫秒
package com.demo;class MyThread implements Runnable{public void run(){for(int i = 0; i < 4; i++){try {System.out.println(Thread.currentThread().getName()+ "休眠0.5秒!");Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("當前啟動並執行線程名稱: "+ Thread.currentThread().getName());}}}public class demo {public static void main(String[] args){MyThread mt1 = new MyThread(); Thread th = new Thread(mt1, "線程A"); System.out.println("\n Thread is starting"); th.start(); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} System.out.println("\n主線程已經休眠2s "+ Thread.currentThread().getName());}}
運行結果如下:
Thread is starting
線程A休眠0.5秒!
當前啟動並執行線程名稱: 線程A
線程A休眠0.5秒!
當前啟動並執行線程名稱: 線程A
主線程已經休眠1s main
線程A休眠0.5秒!
當前啟動並執行線程名稱: 線程A
線程A休眠0.5秒!
當前啟動並執行線程名稱: 線程A
從運行結果可以分析,當線程A休眠1s後,主線程即也已經休眠1s,當前啟動並執行線程為主線程main,接下來線程A繼續運行。