Future接口学习

  1. 使用
java 复制代码
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<Integer> future = executorService.submit(() -> {
    // 执行一些计算任务
    Class<?> clazz = Class.forName("com.example.demo.dao.ItemDao");
    System.out.println("Task executed by thread: " + Thread.currentThread().getName());
    return 42;
});

Object o = future.get();
System.out.println("Result from task: " + o);
executorService.shutdown();

上述代码首先创建了一个固定核心线程数(最大线程数)大小的线程池。然后调用ExecutorService的submit方法执行一个有返回值的callable任务,该方法返回一个实现Future接口的对象。然后通过future.get()方法获取任务的执行结果。最后关闭线程池。

  1. 第一行解读
java 复制代码
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

第一行ExecutorService executorService = Executors.newFixedThreadPool(10);调用了Executors的newFixedThreadPool方法。该方法调用线程池的构造函数创建ThreadPoolExecutor对象。核心线程数和最大线程数均为nThreads。非核心线程存活时间为0L,单位为毫秒。任务队列为LinkedBlockingQueue。

  1. submit方法解读
java 复制代码
public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}

该方法传入要执行的任务task。使用newTaskFor将task封装为RunnableFuture对象。然后调用execute方法执行任务task。该处execute方法调用的是线程池的execute的方法。task的返回值会被赋值给FunnableFuture中的outcome变量。用户使用future.get()方法时,会获取到outcome的值。

  1. future.get()方法详解
java 复制代码
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

该方法关键逻辑为report方法。

java 复制代码
private V report(int s) throws ExecutionException {
    Object x = outcome;
    if (s == NORMAL)
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    throw new ExecutionException((Throwable)x);
}

report方法根据任务task执行的状态,返回outcome或者异常。

相关推荐
BK贝壳1 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
进击的荆棘1 小时前
Linux网络——传输层协议UDP
linux·运维·服务器·网络·udp
吴名氏.2 小时前
全栈跃迁:Java 后端 27 讲【3】Vue3工程化脚手架
java·开发语言·springboot·全栈工程师
codeejun2 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
JellyfishMIX3 小时前
AgentScope-Java 核心机制(内循环) ReAct loop 源码分析
java·后端·agent
小此方4 小时前
QT从入门到精通(一)Qt新手保姆级教程:从官网安装到项目实战,四步带你彻底搞懂Qt框架
开发语言·qt
Rain的Java大神之路4 小时前
Spring Boot 4 把自动配置拆成 47 个模块后,我的 `dependency:tree` 翻天了:一份从排查到治理的完整实战手册
java·spring boot·后端
瑶池酒剑仙5 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
xurileidian5 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
郝学胜-神的一滴7 小时前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy