Ava线程池异常处理
使用ThreadPoolExecutor执行submit提交任务时,某些任务抛出了异常,但线程池没有提示。 也就是说,线程池吃掉了任务的例外。 可以将提交更改为执行执行,可以扩展ThreadPoolExecutor线程池,或者包装提交的任务。
package com.wkcto.threadpool;
import java.util.concurrent.*;
//*
定制线程池类以扩展ThreadPoolExecutor
*/
公共类测试08 {
//自定义线程池类
privatestaticclasstracethreadpollexecutorextendsthreadpoolexecutor {
publictracethreadpollexecutor (intcorepoolsize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,blockingqueueworkquequet )
super(corepoolsize,maximumPoolSize,keepAliveTime,unit,workQueue );
}
定义//方法,包装要执行的任务,接收两个参数,第一个参数接收要执行的任务,第二个参数是Exception异常
publicrunnablewrap (runnable task,Exception exception ) {
返回新运行
@Override
公共语音运行(}
try {
task.run (;
}catch(exceptione ) {
exception.printStackTrace (;
throw e;
}
}
(;
}
重写submit方法
@Override
公共任务(runnable task ) {
returnsuper.submit(wrap(task,new Exception )“客户跟踪异常”)
}
@Override
公共语音执行(runnable command ) {
super.execute(wrap(command,new Exception )“客户跟踪异常”)
}
}
定义//类以实现Runnable接口,并将两个数相除
privatestaticclassdividetaskimplementsrunnable {
private int x;
private int y;
publicdividetask(intx,int y ) {
this.x=x;
this.y=y;
}
@Override
公共语音运行(}
system.out.println (thread.current thread ().getName ) ) '计算:'x'/'y'=' ) (x/y ) );
}
}
publicstaticvoidmain (string [ ] args ) {
//创建线程池
//threadpoolexecutorpoolexecutor=newthreadpoolexecutor (0,Integer.MAX_VALUE,0,TimeUnit.SECONDS,newsynchronds
//使用自定义线程池
threadpoolexecutorpoolexecutor=newtracethreadpollexecutor (0,Integer.MAX_VALUE,0,TimeUnit.SECONDS,newsynchroll
//向线程池添加将两个数相除的任务
for(intI=0; i 5; I ) {
pool executor.submit (newdividetask (10,I );
//pool executor.execute (newdividetask (10,I );
}
}
}