中断线程的睡眠,需要调用 interrupt()方法,把睡眠的线程启动异常处理机制,达到中断的效果,具体代码实现如下 :
public class ThreadTest06 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable2());
t.setName("t");
t.start();
// 希望5秒之后t线程醒来
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 中断 t线程的睡眠 (这种中断睡眠的方式依靠了java的异常处理机制)
t.interrupt(); // 干扰 ,一盆冷水泼过去!!!
}
}
class MyRunnable2 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "==> begin" );
// 睡眠一年
// 因为run()方法在父类中没有抛出任何异常 子类不能比父类抛出更多的异常 不能throws 所以以下程序只能try/catch
try {
Thread.sleep(1000 * 60 *60 *24 * 365);
} catch (InterruptedException e) {
// 打印异常信息
e.printStackTrace();
}
// 一年之后才会执行这里
System.out.println(Thread.currentThread().getName() + "==> end" );
}
}