温馨提示×

温馨提示×

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

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

java Executor执行器是什么

发布时间:2026-09-09 16:40:49 来源:亿速云 阅读:83 作者:小樊 栏目:编程语言

在 Java 中,Executor(执行器) 是 Java 并发编程里用于**解耦“任务提交”和“任务执行”**的一套机制和接口,属于 java.util.concurrent 包。


一、Executor 是什么?

Executor 是一个接口,核心作用是:不直接创建或管理线程,而是把“要执行的任务”交给它,由它来决定怎么跑。

核心接口定义

public interface Executor {
    void execute(Runnable command);
}

你只需要:

executor.execute(() -> System.out.println("任务执行"));

而不需要关心:

  • 用哪个线程?
  • 线程什么时候创建?
  • 线程要不要复用?

二、为什么要用 Executor?

不用 Executor(传统方式)

new Thread(() -> {
    // 业务逻辑
}).start();

问题:

  • 线程创建成本高
  • 线程数无法控制
  • 难以管理生命周期

用 Executor

Executor executor = Executors.newFixedThreadPool(10);
executor.execute(task);

好处:

  • 线程复用
  • 统一资源管理
  • 提升性能和稳定性

三、Executor 家族(重点)

1️⃣ Executor(最顶层)

  • 只定义 execute(Runnable)

2️⃣ ExecutorService(最常用)

继承 Executor,增加了:

  • 任务返回结果(Future
  • 关闭线程池
  • 批量提交任务
ExecutorService executor = Executors.newFixedThreadPool(5);

Future<String> future = executor.submit(() -> "hello");

executor.shutdown();

3️⃣ ScheduledExecutorService

支持定时 / 周期任务

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(() -> {}, 5, TimeUnit.SECONDS);

四、常见 Executor 实现(线程池)

通过 Executors 工具类创建:

类型 说明
newFixedThreadPool 固定线程数
newCachedThreadPool 按需创建线程
newSingleThreadExecutor 单线程顺序执行
newScheduledThreadPool 定时任务

⚠️ 实际生产更推荐 手动创建 ThreadPoolExecutor,避免资源失控。


五、Executor vs Thread

对比 Thread Executor
使用方式 手动管理 自动管理
性能
可控性
推荐度

六、一句话总结

Executor 是 Java 中“任务调度和执行”的抽象,线程池是它的核心实现,用来高效、安全地管理并发任务。

如果你愿意,我也可以帮你画一张 Executor 类关系图 或结合 线程池参数 详细讲。

向AI问一下细节

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

AI