线程的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继续运行。