详解Java中多线程异常捕获Runnable的实现
程序员文章站
2024-02-24 11:19:40
详解java中多线程异常捕获runnable的实现
1、背景:
java 多线...
详解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
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!