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

相关推荐
黄毛火烧雪下5 小时前
Java 核心知识点总结(一)
java·开发语言
其实防守也摸鱼6 小时前
软件安全与漏洞--软件安全编码与防御技术理论题库
开发语言·网络·安全·网络安全·软件安全·软件安全与漏洞
x138702859576 小时前
c语言中srtlen(指针使用计算字符长度)、传值和传址调用
c语言·开发语言·算法·visual studio
iCxhust6 小时前
C#进程管理程序
开发语言·汇编·stm32·单片机·c#·微机原理
凡人叶枫6 小时前
Effective C++ 条款28:避免使用 handles 指向对象内部
linux·服务器·开发语言·c++·嵌入式开发
技术小结-李爽6 小时前
【工具】Maven的下载、安装、使用
java·maven
极创信息6 小时前
Linux挖矿病毒深度清理实战教程,从进程隐藏、Rootkit驻留到彻底根除
java·大数据·linux·运维·安全·tomcat·健康医疗
努力成为AK大王6 小时前
并发编程的核心挑战、优化方案与核心知识点总结
java·开发语言·数据库
云烟成雨TD6 小时前
Agent Scope Java 2.x 系列【10】技能(Skill)
java·人工智能·agent
摇滚侠6 小时前
SpringMVC 入门到实战 DispatcherServlet 源码解读 92-95
java·后端·spring·maven·intellij-idea