先说结论
1.调用线程池的excutor()
方法执行任务,如果有异常,线程终止,等待垃圾回收,并在下一次执行任务时,创建新的线程。
2.调用submit()
方法执行任务,如果有异常,作为结果返回,在结果Future
调用get()
方法时抛出,线程仍可复用。
验证
excutor()
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService poolExecutor = new ThreadPoolExecutor(5, 5, 1000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 10; i++) {
poolExecutor.execute(() -> {
System.out.println(Thread.currentThread().getName() + " hello!");
int t = 1 / 0;
});
}
}
结果打印:
可以看到,线程从pool-1-thread-1
创建到 pool-1-thread-10
,说明没有线程复用。
submit()
public static void main(String[] args) throws ExecutionException, InterruptedException {
AtomicInteger id = new AtomicInteger(0);
ExecutorService poolExecutor = new ThreadPoolExecutor(5, 5, 1000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 10; i++) {
Future<?> submit = poolExecutor.submit(() -> {
System.out.print(Thread.currentThread().getName() + " hello!");
int t = 1 / 0;
});
try {
submit.get();
}catch (Exception e) {
System.out.println(" Exception-------" + e.getMessage());
}
}
}
结果打印:
可以看到,一共只创建了5个线程,说明核心线程得到了复用。