- RejectedExecutionException
- 异常场景:当线程池已经关闭,或者线程池达到最大线程数且队列已满,再提交新任务时会抛出该异常。
- 处理方式:
- 调整线程池参数:可以通过增大
corePoolSize
、maximumPoolSize
,或者增大任务队列的容量(如使用LinkedBlockingQueue
并设置更大的容量),从而避免任务被拒绝。例如:
ExecutorService executorService = new ThreadPoolExecutor(
5, // corePoolSize
10, // maximumPoolSize
1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(100) // 增大队列容量
);
- **自定义拒绝策略**:可以通过实现`RejectedExecutionHandler`接口来自定义拒绝策略。例如:
class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// 在这里可以记录日志,或者将任务存储到其他地方等
System.out.println("任务 " + r + " 被拒绝,线程池状态: " + executor);
}
}
ExecutorService executorService = new ThreadPoolExecutor(
5,
10,
1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(10),
new CustomRejectedExecutionHandler()
);
- InterruptedException
- 异常场景:当线程在等待任务执行(如在队列中等待),或者在执行任务过程中被中断时会抛出该异常。
- 处理方式:
- 在任务中处理中断:在实现
Runnable
接口的任务类中,通过Thread.currentThread().isInterrupted()
来检查线程是否被中断,并进行相应的处理。例如:
class MyTask implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 任务逻辑
System.out.println("任务正在执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();// 重新设置中断状态
// 可以在这里进行清理工作等
System.out.println("任务被中断");
break;
}
}
}
}
- **在关闭线程池时正确处理**:在调用`shutdownNow()`方法关闭线程池时,会尝试中断正在执行的任务。可以在任务中合理处理中断,同时在关闭线程池后检查任务的执行情况。例如:
ExecutorService executorService = Executors.newFixedThreadPool(5);
executorService.submit(new MyTask());
List<Runnable> tasks = executorService.shutdownNow();
for (Runnable task : tasks) {
// 可以对被中断的任务进行处理,如重新提交等
System.out.println("被中断的任务: " + task);
}