在使用ThreadPoolExecutor進(jìn)行submit提交任務(wù)時(shí),有的任務(wù)拋出了異常,但是線程池并沒有進(jìn)行提示,即線程池把任務(wù)中的異常給吃掉了,可以把submit提交改為execute執(zhí)行,也可以對(duì)ThreadPoolExecutor線程池進(jìn)行擴(kuò)展.對(duì)提交的任務(wù)進(jìn)行包裝:
package com.wkcto.threadpool;
import java.util.concurrent.*;
/**
* 自定義線程池類,對(duì)ThreadPoolExecutor進(jìn)行擴(kuò)展
*/
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);
}
//定義方法,對(duì)執(zhí)行的任務(wù)進(jìn)行包裝,接收兩個(gè)參數(shù),第一個(gè)參數(shù)接收要執(zhí)行的任務(wù),第二個(gè)參數(shù)是一個(gè)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("客戶跟蹤異常")));
}
}
//定義類實(shí)現(xiàn)Runnable接口,用于計(jì)算兩個(gè)數(shù)相除
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() + "計(jì)算:" + x + " / " + y + " = " + (x/y));
}
}
public static void main(String[] args) {
//創(chuàng)建線程池
// 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<>());
//向線程池中添加計(jì)算兩個(gè)數(shù)相除的任務(wù)
for (int i = 0; i < 5; i++) {
poolExecutor.submit(new DivideTask(10, i));
// poolExecutor.execute(new DivideTask(10, i));
}
}
}