详细求解Java中多线程异常捕获Runnable的实现
1、背景:
Jva多线程异常不扔给主线程,而是自己处理,外部无法捕获异常。 因此,实现了主线程捕获子线程的异常。
2、工具:
实现Runnable接口的LayerInitTask类、ThreadException类、线程安全矢量
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.time unit;
import com.autonavi.PDS.core.incre.impl.layerinittask;
公共类读扩展{
publicstaticvoidmain (string [ ] args ) {
try {
Vector errRet=new Vector (;
executorservicepool=executors.newfixedthreadpool (6;
for(intI=0; i 6; I ) {
pool.execute (newlayerinittask (I,errRet ) );
}
pool.shutdown (;
pool.awaittermination(1,TimeUnit.DAYS );
if(ERRret.size ) ) (0) ) ) ) ) ) ) ) ) )。
System.out.println ('基于返回值捕获: exception );
throw new RuntimeException ('签入失败!' );
}
}catch(exceptione ) {
System.out.println ('慢速异常捕获: exception );
throw new RuntimeException ('签入失败!' );
}
system.out.println(------入住成功,发送工作完成的邮件----);
}
}
package step5.exception;
import java.util.Vector;
publicclasslayerinittaskimplementsrunnable {
private int threadNum;
private Vector errRet;
publiclayerinittask(intnum,Vector errRet ) {
this.threadNum=num;
this.errRet=errRet;
}
@Override
公共语音运行(}
try {
if(this.threadnum==3) {
thrownewruntimeexception (this.thread num ' :数据格式错误.');
}
system.out.println (this.thread num ' :刷表成功) );
}catch(exceptione ) {
this.errRet.add (线程: ) this.threadnum )运行异常! ' );
thrownewruntimeexception (this.thread num ' :表面打磨失败);
}
}
}
5、结果:
exceptioninthread ' pool-1-thread-4 ' Java.lang.runtime exception 3360:的电子表格计算失败
at step5. exception.layerinittask.run (layerinittask.Java :23 ) )。
at Java.util.concurrent.thread pool executor.run worker (unknown source ) )。
at Java.util.concurrent.thread pool executor $ worker.run (unknown source ) )。
at Java.lang.thread.run (unknown source ) )。
签入exceptioninthread ' main ' Java.lang.runtime exception 3360失败。
at step5. exception.thread exception.main (thread exception.Java :27 ) )。
2:刷表成功
1:刷表成功
5:刷表成功
0:刷表成功
4:刷表成功
基于返回值捕获: exception
基于抛出的异常捕获: exception
如果您有任何问题,请留言或在本站社区讨论,并感谢您阅读。 希望对大家有帮助。 谢谢你对本站的支持。