在使用ThreadPoolExecutor進行submit提交任務時,有的任務拋出了異常,但是線程池并沒有進行提示,即線程池把任務中的異常給吃掉了,可以把submit提交改為execute執行,也可以對ThreadPoolExecutor線程池進行擴展.對提交的任務進行包裝:
package com.wkcto.threadpool;
import java.util.concurrent.*;
/**
* 自定義線程池類,對ThreadPoolExecutor進行擴展
*/
public class Test08 {
//自定義線程池類
private static class TraceThreadPollExecutor extends ThreadPoolExecutor{
public TraceThreadPollExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
//定義方法,對執行的任務進行包裝,接收兩個參數,第一個參數接收要執行的任務,第二個參數是一個Exception異常
public Runnable wrap( Runnable task, Exception exception){
return new Runnable() {
@Override
public void run() {
try {
task.run();
}catch (Exception e ){
exception.printStackTrace();
throw e;
}
}
};
}
//重寫submit方法
@Override
public Future submit(Runnable task) {
return super.submit(wrap(task, new Exception("客戶跟蹤異常")));
}
@Override
public void execute(Runnable command) {
super.execute(wrap(command, new Exception("客戶跟蹤異常")));
}
}
//定義類實現Runnable接口,用于計算兩個數相除
private static class DivideTask implements Runnable{
private int x;
private int y;
public DivideTask(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "計算:" + x + " / " + y + " = " + (x/y));
}
}
public static void main(String[] args) {
//創建線程池
// ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
//使用自定義的線程池
ThreadPoolExecutor poolExecutor = new TraceThreadPollExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
//向線程池中添加計算兩個數相除的任務
for (int i = 0; i < 5; i++) {
poolExecutor.submit(new DivideTask(10, i));
// poolExecutor.execute(new DivideTask(10, i));
}
}
}