温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用ExecutorService创建线程

发布时间:2026-09-16 03:01:59 来源:亿速云 阅读:92 作者:小樊 栏目:编程语言

在 Java 中,ExecutorService 是 java.util.concurrent 包提供的线程池框架,用来更方便、可控地创建和管理线程,而不是直接 new Thread()。

下面从基本用法 → 常见创建方式 → 示例代码 → 关闭线程池逐步说明。


一、为什么用 ExecutorService

  • 复用线程,减少创建/销毁开销
  • 控制线程数量,防止资源耗尽
  • 支持任务队列、定时任务、返回值(Future)

二、创建 ExecutorService 的常用方式

1️⃣ 固定大小线程池(最常用)

ExecutorService executor = Executors.newFixedThreadPool(5);

✅ 适合:已知并发量的场景


2️⃣ 单线程线程池

ExecutorService executor = Executors.newSingleThreadExecutor();

✅ 适合:顺序执行任务


3️⃣ 缓存线程池(自动扩容)

ExecutorService executor = Executors.newCachedThreadPool();

✅ 适合:大量短生命周期任务
⚠ 可能创建大量线程


4️⃣ 定时 / 周期任务

ScheduledExecutorService executor =
        Executors.newScheduledThreadPool(3);

✅ 适合:定时任务、心跳、重试


5️⃣ 推荐:手动创建 ThreadPoolExecutor(更可控)

ExecutorService executor = new ThreadPoolExecutor(
        2,                      // 核心线程数
        10,                     // 最大线程数
        60L, TimeUnit.SECONDS,  // 空闲线程存活时间
        new LinkedBlockingQueue<>(100) // 任务队列
);

三、提交任务的方式

1️⃣ 提交 Runnable(无返回值)

executor.execute(() -> {
    System.out.println("线程执行:" + Thread.currentThread().getName());
});

2️⃣ 提交 Callable(有返回值)

Future<Integer> future = executor.submit(() -> {
    return 1 + 1;
});

Integer result = future.get(); // 阻塞获取结果

四、完整示例

import java.util.concurrent.*;

public class ExecutorDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                System.out.println(
                    Thread.currentThread().getName() + " 执行任务");
            });
        }

        executor.shutdown();
    }
}

五、正确关闭线程池(很重要)

executor.shutdown(); // 不再接受新任务
executor.awaitTermination(10, TimeUnit.SECONDS); // 等待任务完成

或强制关闭:

executor.shutdownNow();

六、常见错误

❌ 不关闭线程池(程序不退出)
❌ 用 new Thread() 替代线程池
❌ 缓存线程池处理高并发长任务


如果你愿意,我可以:

  • 用 Spring 中的 @Async 讲线程池
  • 讲 线程池参数怎么配
  • 给一个 生产级线程池模板

你现在是用在什么场景?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手