线程停止:中断线程。 把线程的状态终止,并抛出一个InterruptedException。
package com.shusheng.tihuzhai.test; import java.util.Date; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2018/8/28 10:40 */ public class ThreadStop extends Thread { @Override public void run() { System.out.println("开始执行:" + new Date()); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); System.out.println("线程被终止了"); } System.out.println("结束执行:"+new Date()); } }
package com.shusheng.tihuzhai.test; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2018/8/28 15:08 */ public class ThreadStopTest { public static void main(String[] args) { ThreadStop ts = new ThreadStop(); ts.start(); try { Thread.sleep(3000); ts.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果:
开始执行:Tue Aug 28 15:09:16 CST 2018 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.shusheng.tihuzhai.test.ThreadStop.run(ThreadStop.java:17) 线程被终止了 结束执行:Tue Aug 28 15:09:19 CST 2018