加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java 强制中断线程运行

发布时间:2020-12-14 23:53:37 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 public class Test implements Runnable {public void run() {try {System.out.println("在run()方法中 - 这个线程会运行20秒");Thread.sleep(20000);

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

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()方法中 - 退出");
	}
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读