# Java实战系列 - 线程池中的线程出现异常
2020-01-14 本文已影响0人
柳经年
问题:线程池中的线程执行任务出现异常,该线程接下来的命运如何?
结论:线程会结束,线程池会新建线程替换该线程
验证:编码验证,代码如下
public class ThreadPoolExceptionTest {
// 创建一个核心线程数、最大线程数都为1的线程池,任务队列最大容量为10
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
public static void main(String[] args) {
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 0)));
try {
// 睡眠1秒,让打印结果更明显
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 1)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 2)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 3)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 4)));
}
}
- 打印日志如下:
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.lushwe.thread.ThreadPoolExceptionTest.lambda$main$0(ThreadPoolExceptionTest.java:25)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
pool-1-thread-2 1
pool-1-thread-2 0
pool-1-thread-2 0
pool-1-thread-2 0
- 总结:通过日志线程的线程名称可知,线程执行任务出现异常,该线程会结束,线程池会创建新的线程替换该线程执行其他任务。
本文完。