详解Java中多线程异常捕获Runnable的实现
详解Java中多线程异常捕获Runnable的实现
1、背景:
Java 多线程异常不向主线程抛,自己处理,外部捕获不了异常。所以要实现主线程对子线程异常的捕获。
2、工具:
实现Runnable接口的LayerInitTask类,ThreadException类,线程安全的Vector
3、思路:
向LayerInitTask中传入Vector,记录异常情况,外部遍历,判断,抛出异常。
4、代码:
package step5.exception;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.autonavi.pds.core.incre.impl.LayerInitTask;
public class ThreadException {
public static void main(String[] args) {
try {
Vector<String> errRet = new Vector();
ExecutorService pool = Executors.newFixedThreadPool(6);
for (int i = 0; i < 6; ++i) {
pool.execute(new LayerInitTask(i, errRet));
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.DAYS);
if (errRet.size() > 0) {
System.out.println("根据返回值捕获:exception");
throw new RuntimeException( "入库失败!");
}
} catch (Exception e) {
System.out.println("根据抛出异常捕获:exception");
throw new RuntimeException( "入库失败!");
}
System.out.println("-----入库成功,发成功完成工作邮件--------");
}
}
package step5.exception;
import java.util.Vector;
public class LayerInitTask implements Runnable {
private int threadNum;
private Vector<String> errRet;
public LayerInitTask(int num, Vector<String> errRet) {
this.threadNum = num;
this.errRet = errRet;
}
@Override
public void run() {
try {
if (this.threadNum == 3) {
throw new RuntimeException( this.threadNum + ":数据格式有误.");
}
System.out.println(this.threadNum + ":刷表成功");
} catch (Exception e) {
this.errRet.add("线程:" + this.threadNum + "运行异常!");
throw new RuntimeException( this.threadNum + ":刷表失败");
}
}
}
5、结果:
Exception in thread "pool-1-thread-4" java.lang.RuntimeException: 3:刷表失败 at step5.exception.LayerInitTask.run(LayerInitTask.java:23) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Exception in thread "main" java.lang.RuntimeException: 入库失败! at step5.exception.ThreadException.main(ThreadException.java:27) 2:刷表成功 1:刷表成功 5:刷表成功 0:刷表成功 4:刷表成功 根据返回值捕获:exception 根据抛出异常捕获:exception
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
SpringBoot集成Swagger使用SpringSecurity控制访问权限问题
这篇文章主要介绍了SpringBoot集成Swagger使用SpringSecurity控制访问权限问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-05-05
SpringMVC @ResponseBody 415错误处理方式
这篇文章主要介绍了SpringMVC @ResponseBody 415错误处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-11-11
Spring mvc整合mybatis(crud+分页插件)操作mysql
这篇文章主要介绍了Spring mvc整合mybatis(crud+分页插件)操作mysql的步骤详解,需要的朋友可以参考下2017-04-04
Java CharacterEncodingFilter过滤器的理解和配置案例详解
这篇文章主要介绍了Java CharacterEncodingFilter过滤器的理解和配置案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08
SpringBoot集成selenium实现自动化测试的代码工程
Selenium 是支持web 浏览器自动化的一系列工具和[库] 它提供了扩展来模拟用户与浏览器的交互,用于扩展浏览器分配的分发,本文给大家介绍了SpringBoot集成selenium实现自动化测试的代码工程,需要的朋友可以参考下2024-08-08


最新评论