submit 与 execute
- 一、前言
- 二、核心区别
- 三、代码示例
-
- [3.1 execute() 抛出异常新创建线程示例](#3.1 execute() 抛出异常新创建线程示例)
- [3.2 execute() 与 submit() 一览](#3.2 execute() 与 submit() 一览)
一、前言
本章节介绍线程池下 submit 与 execute 的区别
二、核心区别
- submit() 会抛出异常,execute() 不会抛出异常;如果抛出异常会导致线程终止, 线程终止后线程池如果需要创建线程,会创建一个新的线程
- submit() 可以传入 Runnable 和 Callable, execute() 只能传入 Runnable
三、代码示例
3.1 execute() 抛出异常新创建线程示例
java
ThreadPoolExecutor executor = new ThreadPoolExecutor(
// 核心线程 2
2,
// 最大线程 2
2,
// 过期时间 1 小时
1,
TimeUnit.HOURS,
// 阻塞队列 10
new ArrayBlockingQueue<>(10),
// 线程工厂, 自定义了线程名字, 方便观察效果
new ThreadFactory() {
private static final AtomicInteger number = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "custom-" + number.getAndIncrement());
}
},
// 拒绝策略
new ThreadPoolExecutor.DiscardOldestPolicy());
// 提交 10 个任务, 当 thread 最后是 2 的时候抛出异常
// 也就是观察一下当 custom-2 打印错误之后是否还有 2 在执行任务
for (int i = 1; i <= 10; i++) {
executor.execute(() -> {
String threadName = Thread.currentThread().getName();
if (threadName.endsWith("2")) {
throw new RuntimeException("线程信息错误" + threadName);
}
System.out.println("haha" + threadName);
});
}
ThreadUtil.waiting();
3.2 execute() 与 submit() 一览
java
// 运行这个 Runnable, 无返回值
void execute(Runnable command);
// 提交一个 Callable, 通过 Future 获取结果
Future<T> submit(Callable<T> task)
// 提交一个 Runnable, 任务结果后返回 result 通过 Future 获取
Future<T> submit(Runnable task, T result)
// 提交一个 Runnable, 虽然 Future 泛型是个 ?, 但是返回的是一个 Void
Future<?> submit(Runnable task);