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或者异常。

相关推荐
嘻哈∠※2 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
WWJA王文举2 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
zhanghaha13142 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
我是谁??3 小时前
Ubuntu22.04更换清华源
linux·运维·服务器
白狐_7983 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
圣殿骑士-Khtangc3 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
zander2583 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅3 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
qq_448011164 小时前
C语言中的动态内存分配
c语言·开发语言·php
这个DBA有点耶4 小时前
数据库一体机架构演进:从硬件堆叠到软硬深度耦合
服务器·网络·数据库·硬件架构·运维开发·database·数据库架构