详解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 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 errRet;
public LayerInitTask(int num, Vector 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
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环