线程池正常运行的情况下,如果忽然某条线程执行任务时,抛出了异常,这个时候线程池会怎么处理呢?
准备测试代码(测试代码需要jdk1.8以上)
public class ThreadThrowsExceptionTest {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), new DefaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
executorService.submit(() -> {
System.out.println("线程" + Thread.currentThread().getName() + "准备抛空指针异常了");
throw new NullPointerException("线程抛出空指针啦");
});
IntStream.range(0, 4).forEach(index -> executorService.submit(() -> System.out.println("线程" + Thread.currentThread().getName() + "执行了任务" + index)));
}
//这里借用了Executors中DefaultThreadFactory,进行了简单修改,方便测试
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
System.out.println("创建线程了" + t.getName());
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority(