java 强制中断线程运行
发布时间:2020-05-24 18:19:52 所属栏目:Java 来源:互联网
导读:java 强制中断线程运行
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 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()方法中 - 退出");
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
