线程池的任务中,会出现一种特殊的异常。在结果上没有输出,但是程序不会抛出报错,这就需要我们对这种异常进行处理。我们先从通过一个实例来分析这种异常的情况,然后为大家带来处理线程池异常的两种方法及代码实例部分。接下来我们看看线程池发生异常的原理和解决办法吧。
1.异常情况
ExecutorServicethreadPool=Executors.newFixedThreadPool(5);
for(inti=0;i<5;i++){
threadPool.submit(()->{
System.out.println("currentthreadname"+Thread.currentThread().getName());
Objectobject=null;
System.out.print("result##"+object.toString());
});
}
虽然没有结果输出,但是没有抛出异常,所以我们无法感知任务出现了异常。
2.异常处理方法
(1)在run方法上增加异常处理
publicclassFutureTask<V>implementsRunnableFuture<V>{
...
publicvoidrun(){
if(state!=NEW||
!UNSAFE.compareAndSwapObject(this,runnerOffset,
null,Thread.currentThread()))
return;
try{
Callable<V>c=callable;
if(c!=null&&state==NEW){
Vresult;
booleanran;
try{
result=c.call();
ran=true;
}catch(Throwableex){
result=null;
ran=false;
setException(ex);
}
if(ran)
set(result);
}
}finally{
//runnermustbenon-nulluntilstateissettledto
//preventconcurrentcallstorun()
runner=null;
//statemustbere-readafternullingrunnertoprevent
//leakedinterrupts
ints=state;
if(s>=INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
publicVget()throwsInterruptedException,ExecutionException{
ints=state;
if(s<=COMPLETING)
s=awaitDone(false,0L);
returnreport(s);
}
privateVreport(ints)throwsExecutionException{
Objectx=outcome;
if(s==NORMAL)
return(V)x;
if(s>=CANCELLED)
thrownewCancellationException();
thrownewExecutionException((Throwable)x);
}
}
(2)使用UncaughtExceptionHandler处理未捕获异常
Threadthread=newThread(()->{
System.err.println(3/2);
System.err.println(3/0);
});
thread.setUncaughtExceptionHandler(newThread.UncaughtExceptionHandler(){
@Override
publicvoiduncaughtException(Threadt,Throwablee){
System.err.println(Thread.currentThread().getName()+"==>"+e.getMessage());
}
});
thread.start();
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容