面试题答案
一键面试在Java线程池中,使用ThreadPoolExecutor
创建线程池执行任务时可能出现以下异常:
- RejectedExecutionException:当线程池已经关闭或者线程池达到饱和状态(线程数达到最大线程数且任务队列已满),再提交新任务时会抛出该异常。 示例:
import java.util.concurrent.*;
public class ThreadPoolExceptionExample {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1));
try {
executor.submit(() -> System.out.println("Task 1"));
executor.submit(() -> System.out.println("Task 2"));
executor.submit(() -> System.out.println("Task 3"));
} catch (RejectedExecutionException e) {
System.err.println("Task rejected: " + e.getMessage());
} finally {
executor.shutdown();
}
}
}
- NullPointerException:如果向
ThreadPoolExecutor
的构造函数传入null
参数,比如null
的任务队列,会抛出该异常。 示例:
import java.util.concurrent.*;
public class ThreadPoolNullPointerExceptionExample {
public static void main(String[] args) {
try {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
1, 1,
0L, TimeUnit.MILLISECONDS,
null);
} catch (NullPointerException e) {
System.err.println("Null parameter exception: " + e.getMessage());
}
}
}
- IllegalArgumentException:当向
ThreadPoolExecutor
的构造函数传入不合法的参数时,比如核心线程数小于0、最大线程数小于等于0或者最大线程数小于核心线程数等,会抛出该异常。 示例:
import java.util.concurrent.*;
public class ThreadPoolIllegalArgumentExceptionExample {
public static void main(String[] args) {
try {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
-1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
} catch (IllegalArgumentException e) {
System.err.println("Illegal argument exception: " + e.getMessage());
}
}
}
捕获这些异常的通用代码结构为:
try {
// 提交任务到线程池
executor.submit(task);
} catch (RejectedExecutionException e) {
// 处理任务被拒绝的情况
System.err.println("Task rejected: " + e.getMessage());
} catch (NullPointerException e) {
// 处理空指针异常
System.err.println("Null parameter exception: " + e.getMessage());
} catch (IllegalArgumentException e) {
// 处理非法参数异常
System.err.println("Illegal argument exception: " + e.getMessage());
}