1、背景:
Java 多线程异常不向主线程抛,自己处理,外部捕获不了异常。所以要实现主线程对子线程异常的捕获。
2、工具:
实现Runnable接口的LayerInitTask类,ThreadException类,线程安全的Vector
3、思路:
向LayerInitTask中传入Vector,记录异常情况,外部遍历,判断,抛出异常。
4、代码:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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("-----入库成功,发成功完成工作邮件--------");
}
}
|
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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、结果:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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
|
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/q_l_s/article/details/70159749
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 66
-
2025-05-29 107
-
2025-05-25 80
-
2025-05-25 14
-
Java中ArrayList在foreach里remove的问题详析
2025-05-29 65
热门评论

