并发基础之Callable与Future
创始人
2025-05-31 14:48:16
0

目录

    • 前言
    • 浅析Callale接口
      • Callale源码分析
      • Callale简单演示
    • 浅析Future接口
      • Future源码分析
      • Future简单演示
    • 结语

前言

在多线程编程中,我们一般会根据实际业务场景来创建线程实现功能。当然创建线程的方式也有很多,比如继承Thread类、实现Runable接口或直接根据Executors类创建线程池获取线程。但是继承Thread类和实现Runable并不能获取线程执行结果,如果我们有需求要获取执行结果怎么处理呢?答案就是今天的主角——Callale与Future接口。

浅析Callale接口

Callale源码分析

进入JUC 包下找到 Callable 接口

@FunctionalInterface
public interface Callable {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception;
}

如上源码所示,Callable 接口内部有个call() 方法,该方法可以返回结果,如果有异常情况会抛出异常。call() 方法是 Callable 接口唯一且核心方法,我们在实际开发场景中,在call() 方法中写入具体逻辑代码并可以返回我们需要的结果。

我们继续查看 Callable 接口实现类
在这里插入图片描述

如图所示我们有很多工具类实现了 Callable接口,比如比较常见的 RunableAdapter、TaskCallable等等工具类,在实际业务场景我们可以任意选用我们喜欢的方式实现自己的多线程功能。

Callale简单演示

比如我们现在需要在业务场景中使用多线程执行,并且需要返回执行中的一个结果。那么,我们直接实现Callable即可:

/*** TestCallable* @author senfel* @date 2023/3/20 11:06 * @return void*/
@Test
public void TestCallable() throws Exception{Callable callable = new Callable() {@Overridepublic String call() throws Exception {//具体的业务场景省略 //......//模拟返回执行结果return "测试1";}};//获取执行结果String call = callable.call();//打印结果在控制台System.err.println(call);
}

这里我们直接是简便的编码方式,当前不怕麻烦的同学可以单独写一个类实现Callable接口,然后在实例化自身的线程类并调用。

浅析Future接口

Future源码分析

上文我们讲到了实现Callable接口创建线程并获取执行接口,下面我们看看实现Future 接口方式有何异同。我们先来看源码:

package java.util.concurrent;/**
* Future接口
*/
public interface Future {/*** 取消*/boolean cancel(boolean mayInterruptIfRunning);/*** 获取是否取消*/boolean isCancelled();/*** 任务是否完成*/boolean isDone();/*** 循环等待执行结果*/V get() throws InterruptedException, ExecutionException;/*** 超时等待执行结果*/V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
}

如上源码所示,我们发现 Future 接口内部提供了很多很多的操作方法。比如 cancel() 取消执行、isCancelled () 获取是否取消状态、isDone() 任务是否完成,当然还有我们最重要的 get() 获取执行结果的方法。

看到这里我们不难发现,Future 接口比 Callable接口多了很多很多的操作线程的方法。这些操作方式可以使得线程操作更加灵活,也能够让开发人员适用跟过的业务场景编码。我想说,看到Future 接口我就不想用 Callable了呢。

继续查看Futrue实现类,我们看看有哪些
在这里插入图片描述

如图所示,有很多的实现类。其中有大家不陌生并且经常使用到的ForkJoinTask、FutureTask,这里两个实现类应该算是在多线程开发中经常使用的吧。

我们选一个实现类进入查看Future具体的实现方式吧,我们就用 FutureTask 开探究为啥 Future要比Callable多那么多的操作方法。

进入 JUC FutureTask 查看源码

public interface RunnableFuture extends Runnable, Future {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/void run();
}
public class FutureTask implements RunnableFuture {/** 执行线态* NEW -> COMPLETING -> NORMAL* NEW -> COMPLETING -> EXCEPTIONAL* NEW -> CANCELLED* NEW -> INTERRUPTING -> INTERRUPTED*/private volatile int state;private static final int NEW          = 0;private static final int COMPLETING   = 1;private static final int NORMAL       = 2;private static final int EXCEPTIONAL  = 3;private static final int CANCELLED    = 4;private static final int INTERRUPTING = 5;private static final int INTERRUPTED  = 6;/** The underlying callable; nulled out after running */private Callable callable;/** The result to return or exception to throw from get() */private Object outcome; // non-volatile, protected by state reads/writes/** The thread running the callable; CASed during run() */private volatile Thread runner;/** Treiber stack of waiting threads */private volatile WaitNode waiters;/*** Returns result or throws exception for completed task.** @param s completed state value*/@SuppressWarnings("unchecked")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);}/*** Creates a {@code FutureTask} that will, upon running, execute the* given {@code Callable}.** @param  callable the callable task* @throws NullPointerException if the callable is null*/public FutureTask(Callable callable) {if (callable == null)throw new NullPointerException();this.callable = callable;this.state = NEW;       // ensure visibility of callable}/*** Creates a {@code FutureTask} that will, upon running, execute the* given {@code Runnable}, and arrange that {@code get} will return the* given result on successful completion.** @param runnable the runnable task* @param result the result to return on successful completion. If* you don't need a particular result, consider using* constructions of the form:* {@code Future f = new FutureTask(runnable, null)}* @throws NullPointerException if the runnable is null*/public FutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);this.state = NEW;       // ensure visibility of callable}public boolean isCancelled() {return state >= CANCELLED;}public boolean isDone() {return state != NEW;}public boolean cancel(boolean mayInterruptIfRunning) {if (!(state == NEW &&UNSAFE.compareAndSwapInt(this, stateOffset, NEW,mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))return false;try {    // in case call to interrupt throws exceptionif (mayInterruptIfRunning) {try {Thread t = runner;if (t != null)t.interrupt();} finally { // final stateUNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);}}} finally {finishCompletion();}return true;}}

如上源码 FutureTask 实现了 RunnableFuture 接口,RunnableFuture 又是实现了Runable和Future,所以FutureTask自然拥有了Future的功能。但是我们也看到FutureTask 构造方法需要传入实例化线程,这里可以是 Callable 实现的线程。分析到这里我们就明白了什么Future 要比 Callable多那么多的方法?原因其实就是Future是对线程操作的升华,不仅仅创建执行线程,更多的是对创建线程执行状态的维护。

Future简单演示

既然上文我们分析了FutureTask ,这里就用FutureTask 简单演示吧

    /*** TestFutureTask* @author senfel* @date 2023/3/20 11:34* @return void*/@Testpublic void TestFutureTask() throws Exception {//实例化FutureTask,并传入一个用Callable实现的线程FutureTask task = new FutureTask(new Callable() {@Overridepublic String call() throws Exception {return "TestFutureTask";}});//运行任务task.run();//获取执行结果String s1 = task.get();//结果打印System.err.println(s1);}
}

这里我们直接也是简便的编码方式,当前不怕麻烦的同学可以单独写一个类实现Callable接口,然后在实例化FutrueTask时传入。

当然,在使用Futrue过程中我们推荐线程池获取Futrue的方式

/*** TestCallableByPool** @author senfel* @date 2023/3/20 11:43 * @return void*/
@Test
public void TestCallableByPool() throws Exception{//创建一个定长线程池ExecutorService executorService = Executors.newFixedThreadPool(10);//获取FutureFuture future = executorService.submit(new Callable() {@Overridepublic String call() throws Exception {//具体的业务场景省略//......//模拟返回执行结果return "TestCallableByPool";}});String s = future.get();System.err.println(s);
}

结语

在多线程编码需要获取线程执行结果的情况下,我们推荐使用实现Futrue 接口的方式,它比Callable方式多了很多的操作执行线程的方法,比如 cancel() 取消执行、isCancelled () 获取是否取消状态、isDone() 任务是否完成等等。在实际的开发中,我们也推荐使用多线程来创建Futrue获取执行结果。

相关内容

热门资讯

布局低空,布局引领全球的万亿赛... 当前新质生产力相关的产业已成为最引人注目成长赛道,在众多新质生产力产业中,低空经济是少有的由我国引领...
特斯拉超级充电站餐厅开业,马斯... IT之家 7 月 22 日消息,特斯拉超级充电站餐厅(Supercharger Diner)今日在洛...
算力需求持续火热,人工智能ET... 截至2025年7月22日收盘,中证人工智能产业指数(931071)下跌0.82%。成分股方面涨跌互现...
一图解码:港股IPO一周回顾 ... 过去一周(2025.7.14-7.20),港股IPO市场共有3家公司递交了上市申请,分别为麦济生物、...
最强赛道,呈两极分化!有的猛增... 创新药赛道行情爆火的同时,医药基金的“留人能力”却呈现两极分化。 券商中国记者注意到,根据最新披露的...
菲律宾要失望了,知情人士:美国... 本月初,美国总统特朗普公布多国关税税率,其中,对菲律宾产品征收的“对等关税”从今年4月公布的17%升...
2025年广东省乡村旅游消费趋... 2024年,广东省乡村旅游接待游客5.1亿人次,占全省总旅游接待人次的58.6%;乡村旅游收入达37...
高晓峰:趋势线守卫战告捷 黄金... 来源:市场资讯 7月22日,国际黄金本周初受美元走软及贸易局势影响强势走高。美国通胀数据低于预期,黄...
原创 美... 在我们的日常生活中,电力早已融入了方方面面。我们习惯了出门时确保手机电量充足,家里需要WiFi的连接...
复牌“摘帽”!基金公司第一时间... 【导读】复牌当天再遭基金公司“补刀”,招商基金下调诺泰生物估值 中国基金报记者 若晖 因涉及财务造假...
24年老将、前公募总经理“奔私... 【导读】携手老同事创业,原公募总经理宋小龙备案上海理泉私募基金 中国基金报记者 吴君 又见公募基金总...
科创板开市6周年:已拥有589... 7月22日,科创板迎来开市6周年。这个中国资本市场最年轻的板块已经拥有589家上市公司、超7万亿元总...
科创板六周年!上市公司“掌门人... 【导读】 2025年7月22日,中国资本市场这片热土上,一块名为“科创板”的“试验田”已悄然耕耘六载...
聚焦"稳"... 北京2025年7月22日-- 当前,中国经济正经历深刻转型升级,企业面临市场波动、竞争加剧等多重挑战...
华泰柏瑞港股通时代机遇混合A:... AI基金华泰柏瑞港股通时代机遇混合A(011355)披露2025年二季报,第二季度基金利润292.6...
致179人遇难!韩国12·29... 据韩国《韩民族日报》7月21日报道,韩国国土交通部下属的“航空铁路事故调查委员会”7月19日就去年1...
卧龙电驱:7月21日融券卖出6... 证券之星消息,7月21日,卧龙电驱(600580)融资买入4.49亿元,融资偿还5.59亿元,融资净...
破解堵点卡点,做强国内大循环 国务院常务会议7月16日召开,研究做强国内大循环重点政策举措落实工作,并作出一系列针对性部署。会议指...