线程停止
来源:互联网 发布:ug编程教程百度云 编辑:程序博客网 时间:2024/05/21 22:22
大多数停止一个线程的操作使用Thread.interrupt()方法,尽管方法的名称是“停止”的意思。但是这个方法不会终止一个正在运行的线程,还需要假如一个判断才可以完成线程的停止。
利用异常可以停止线程
package com.eroadsf.thread;public class MyThread extends Thread { @Override public void run() { super.run(); try { for (int i = 0; i < 500000; i++) { //判断当前线程是否停止,如果发现是停止状态了就直接抛出异常 if (this.interrupted()) { System.out.println("我要退出了"); throw new InterruptedException(); } System.out.println("i=" + (i + 1)); } System.out.println("不好意思还活着"); } catch (InterruptedException e) { System.out.println("进Mythread.java 类run方法中的catch了"); e.printStackTrace(); } }}
package com.eroadsf.thread;public class Run { public static void main(String[] args) { try { MyThread thread=new MyThread(); thread.start(); Thread.sleep(1000); //interrupt 打一个停止的标记 thread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } }}
阅读全文
0 0
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 线程停止
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 停止线程
- 线程停止
- 利用interrupt停止线程
- mysql日志形式
- 【redis-demo】使用Jedis api 实现后端缓存优化
- jquery之qq邮箱分享
- 【Python】Scrapy Request传参数方法
- POJ2777【线段树】
- 线程停止
- MongoDB 写安全(Write Concern)
- Java GC 日志详解
- gitlab 快速安装和注意事项
- 文章标题
- Linux安装PHP MongoDB扩展(亲测)
- 三极管那点事
- mysql 插入中文报错: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value...
- 【计算机算法分析】动态规划法——矩阵连乘问题