一个sleep()方法的程序。
原文:http://http://blog.csdn.net/wangyuetingtao/article/details/8242343
package Thread;
import java.util.Date;
public class TestSleep {
public static void main(String[] args) {
myThread mythread = new myThread();
mythread.start();
try {
Thread.sleep(10000);
} catch (Exception e) {
// TODO: handle exception
return;
}
mythread.interrupt();
}
}
class myThread extends Thread{
@Override
public void run(){
while (true) {
System.out.println(new Date());
try
{
sleep(1000);
}
catch(Exception exception)
{
return;
}
}
}
}
以下是结果:
Fri Mar 18 19:09:02 CST 2016
Fri Mar 18 19:09:03 CST 2016
Fri Mar 18 19:09:04 CST 2016
Fri Mar 18 19:09:05 CST 2016
Fri Mar 18 19:09:06 CST 2016
Fri Mar 18 19:09:07 CST 2016
Fri Mar 18 19:09:08 CST 2016
Fri Mar 18 19:09:09 CST 2016
Fri Mar 18 19:09:10 CST 2016
Fri Mar 18 19:09:11 CST 2016
注意:sleep()方法 需要捕获异常。因为sleep方法会抛出interrruptedException异常。该异常表示当线程被打断是,该线程的停止休眠。
上述程序的执行过程:程序启动,主线程和mythread线程启动,mythread线程开始每秒打印一次当前系统时间,然后Thread.sleep(10000)执行,主线程休眠10s ,但是子线程依然执行,10s后,主线程重新启动,执行interrupt方法,然后子线程抛出异常,然后return,子线程结束,主线程结束,程序结束。