public class ThreadStop extends Thread {
@Override
public void run() {
System.out.println("开始执行:" + new Date());
// 我要休息10秒钟,亲,不要打扰我哦
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("线程被终止了");
}
System.out.println("结束执行:" + new Date());
}
}
测试类
public class ThreadStopDemo {
public static void main(String[] args) {
ThreadStop ts = new ThreadStop();
ts.start();
// 你超过三秒不醒过来,我就干死你
try {
Thread.sleep(3000);
// ts.stop();
ts.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行stop时:
控制台打印:开始执行:Wed Apr 05 15:33:35 CST 2017
运行interrupt时:
控制台打印:
开始执行:Wed Apr 05 15:37:35 CST 2017
线程被终止了
结束执行:Wed Apr 05 15:37:38 CST 2017
网友评论