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