当前位置:

Executor框架

机器助手 |  2025-07-13
 100人浏览

一、Executor框架的作用

Executor是线程池的调度工具,线程池是Executor的一部分

二、Executor框架的结构

Executor框架由三大部分组成

1、任务:即被执行任务需要实现的接口:Runnable接口或Callable接口

2、线程池:主要通过ExecutorService接口调用线程池,有2个关键实现类ThreadPoolExecutor和ScheduledThreadPoolExecutor

3、异步计算的结果:Future接口及其实现类FutureTask

三、Executor框架的执行过程

1、通过实现Runnable接口或Callable接口创建任务

2、通过Executors的工厂方法创建线程池

3、通过ExecutorService.submit()提交一个有返回结果的任务,返回类型为一个实现Future接口的对象;或通过ExecutorService.execute()方法执行一个没有返回结果的任务

4、通过FutureTask.get()获取返回结果(如果有)

四、Runnable与Callable的区别

Runnable没有返回结果,即没有return语句;Callable有返回结果

可以通过Executors工厂类将Runnable封装为一个Callable对象

方法 描述
Callable

五、execute与submit的用法与区别

execute执行后没有返回结果,只有1种用法

方法 描述
void execute(Runnable command) 常规使用方法,用没有返回值的execute执行没有返回值的Runnable任务

submit执行后有返回结果,有3种用法

方法 描述
Future submit(Callable task) 常规使用方法,传入有返回值的callable任务,最终返回task的返回值
Future submit(Runnable task, T result) 由于Runnable没有返回值,但是可以自定义一个返回值用于返回
Future submit(Runnable task) 强行使用submit执行Runnable方法,忽略返回值

六、ThreadPoolExecutor的3种类型

ThreadPoolExecutor是最常用的线程池,通常使用工厂类Executors创建,有3种类型

1、FixedThreadPool

创建固定线程数的线程池,适用于为了满足资源管理需要,而需要限制线程数量的场景,即负载较重的服务器

2、SingleThreadPool

创建使用单个线程的线程池,保证顺序地执行各个任务

3、CachedThreadPool

创建没有线程数量限制的线程池,适用于执行很多短期异步任务的场景,即负载较轻的服务器。有耗尽资源的风险

七、ScheduledThreadPoolExecutor的2种类型

ScheduledThreadPoolExecutor用于执行延迟任务或定期任务,有2种类型

1、ScheduledThreadPoolExecutor

包含多个线程,适用于需要多个后台线程执行延迟或周期任务的场景

2、SingleThreadScheduledExecutor

仅有一个线程,适用于需要单个后台线程执行延迟或周期任务,并且需要保证任务的顺序执行的场景

八、Executor框架使用示例


 
public class Main { public static void main(String[] args) throws InterruptedException { // 创建线程池 ExecutorService threadPool = Executors.newFixedThreadPool(5); // 通过execute方法用线程池执行一个任务 threadPool.execute(() -> System.out.println("Task1")); // 通过submit方法可获取线程执行结果 Future<Object> future = threadPool.submit(() -> "Task2"); try { Object obj = future.get(); System.out.println(obj); // 可设置超时时间 // future.get(1, TimeUnit.SECONDS); } catch (InterruptedException e) { System.out.println("InterruptedException"); } catch (ExecutionException e) { System.out.println("ExecutionException"); } finally { // 关闭线程池 threadPool.shutdown(); // 或者使用shutdownNow()方法 // threadPool.shutdownNow(); // 如果调用了shutdown()或者shutdownNow(),那么isShutdown()就为真 System.out.println(threadPool.isShutdown()); // 只有当所有任务都关闭后isTerminated()才为真 System.out.println(threadPool.isTerminated()); // sleep1秒让线程池有足够时间关闭 Thread.sleep(1); System.out.println(threadPool.isTerminated()); } } }

文章评论