线程池-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);
相关推荐
山甫aa8 分钟前
JavaWeb后端开发学习手册
java·开发语言·数据库·学习·mysql·springboot·web
鱼鳞_17 分钟前
热门八股-JVM
java·jvm
ly768919 分钟前
XML 从入门到实践:语法、命名空间、XPath、XSD 与 Java 安全解析
xml·java·python
长谷深风11128 分钟前
好的 Tool Schema,不是字段越全越好
java·大数据·人工智能·ai agent·agent工作流·智能体设计·ai产品设计
IT 行者30 分钟前
用 HiddenHttpMethodFilter 解决浏览器不支持 PUT/DELETE/PATCH 的问题
java·spring
晚安code34 分钟前
Redis 内存淘汰策略实战:什么时候淘汰、怎么选、怎么防缓存击穿
java·redis·缓存
goyeer1 小时前
Liunx日志管理与journalctl
java·linux·运维·服务器·运维开发·信息化·信息化企业管理
tianyu2342 小时前
Java 正则表达式终极指南:从 Pattern 到 Matcher,从双重转义到性能优化,一篇全搞定
java·开发语言·正则表达式·group·find·pattern·matcher
Emily156853598704 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
就叫_这个吧9 小时前
Java递归方法实现面包屑导航
java·开发语言