java 强制中断线程运行
2018-07-20 来源:open-open
public class Test implements Runnable {
public void run() {
try {
System.out.println("在run()方法中 - 这个线程会运行20秒");
Thread.sleep(20000);
System.out.println("在run()方法中 - 继续运行");
} catch (InterruptedException x) {
System.out.println("在run()方法中 - 中断线程"); // 捕捉到中断异常,立即停止运行
return;
}
System.out.println("在run()方法中 - 休眠之后继续完成");
System.out.println("在run()方法中 - 正常退出");
}
public static void main(String[] args) {
Test si = new Test();
Thread t = new Thread(si);
t.start();
// 在此休眠是为确保线程能运行一会
try {
Thread.sleep(2000);
} catch (InterruptedException x) {
}
System.out.println("在main()方法中 - 中断其它线程");
t.interrupt(); // 实际上t线程要运行20秒,但是在主线程中2秒后就终止了t线程
System.out.println("在main()方法中 - 退出");
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐