线程池-submit 与 execute

submit 与 execute


一、前言

本章节介绍线程池下 submit 与 execute 的区别


二、核心区别

  1. submit() 会抛出异常,execute() 不会抛出异常;如果抛出异常会导致线程终止, 线程终止后线程池如果需要创建线程,会创建一个新的线程
  2. 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);
相关推荐
广师大-Wzx8 小时前
JavaWeb:后端部分
java·开发语言·spring·servlet·tomcat·maven·mybatis
dishugj8 小时前
HANA数据库常用命令总结
java·前端·数据库
MacroZheng8 小时前
横空出世!IDEA最强MyBatis插件来了,功能很全!
java·后端·mybatis
zhangjw348 小时前
第9篇:Java集合框架入门,List详解:ArrayList与LinkedList底层彻底吃透
java·开发语言·list
大大杰哥8 小时前
Java集合框架(List/Set/Queue)核心总结与代码示例
java·数据结构
深蓝轨迹8 小时前
RedisTemplate 核心操作API汇总(Spring Data Redis)
java·redis·spring
Cat_Rocky9 小时前
K8s RBAC认证 简单讲
java·docker·kubernetes
一只IT攻城狮9 小时前
️ Spring Boot 文件上传,防御恶意文件攻击
java·spring boot·web安全
ch.ju9 小时前
Java Programming Chapter 3——Subscript of the array
java·开发语言
雨落在了我的手上9 小时前
初识java(三):运算符
java·开发语言