并发基础之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获取执行结果。

相关内容

热门资讯

在大吉订购APP订购交易亏损被...   近期,不少投资者反映在“大吉订购App”上投资白银、铂金等商品遭遇严重亏损。该平台宣称提供现货订...
铂银壹号APP商品订购交易亏损...   许多中小投资者误以为网上的“商品现货订购”是合规合法的理财渠道,殊不知这背后隐藏着巨大的合规风险...
兴鑫淘金APP贵金属订购交易亏...   白银、贵金属或其他商品类投资,除国家批准的正规期货交易场所及持牌期货公司外,市面上大量第三方交易...
铂银掘金APP无资质的违规平台...   铂银掘金等平台的投资者,往往是被“注册送现金”“充值返现券”“首单免亏”等广告话术吸引,进而下载...
八方淘金APP订购交易不合规,...   “八方淘金APP”“铂银掘金APP”“铂银壹号APP”等软件被指以“现货订购”为名,实际采用高杠...
在指尖订购APP订购商品亏损被...   指尖订购APP这类平台,表面是“订购交易”,实则是披着电商外衣的非法期货陷阱。绝大多数投资者被蒙...
在犀贝易购APP做商品订购交易...   市面上打着“现货投资”“贵金属交易”旗号的APP并不少,但真正合规、受监管的平台并不多。犀贝易购...
易达淘金APP虚假商品订购交易...   易达淘金APP存在严重的虚假宣传与违规交易行为。该平台打着“商品订购”的旗号,实则通过不合规的交...
大浪淘金APP白银订购亏损被骗...   大浪淘金APP最隐蔽的套路,在于其完全封闭的内盘交易系统。表面上,它宣称与国际贵金属市场接轨;实...
一品好购APP上订购白银出现亏...   一品好购APP原名“一品订购”,运营方为上海宝智未来信息技术有限公司。近期不少投资者反映在该平台...
九州订购APP贵金属订购投资骗...   九州订购APP正通过抖.音、快手、今日头条等平台大量投放投资广告,用“5元起投”“充值返现”“0...
坚锅淘金APP交易软件并不正规...   当前,市面上大量所谓的“现货商城订购”交易软件,早已偏离了正常的实物商品买卖,演变为高杠杆、高手...
斗金订购APP贵金属期货交易骗...   斗金订购APP的投资者往往被铺天盖地的广告宣传所诱导——注册即送现金、充值返现券等看似诱人的福利...
警惕!云启购APP违规经营,披...   "5元起投、充值返现、稳赚不赔"——这些诱人的广告语背后,可能是一个精心设计的金融陷阱。  近期...
量子淘金APP贵金属投资不合规...   "4元起投""充值返券""月入过万"——这些极具诱惑力的广告语在短视频平台、社交软件上铺天盖地。...
鑫汇智投APP贵金属商品订购骗...   鑫汇智投APP非法期货投资骗局,受害者在投资过程中根本不懂交易,也不去研究和验证这个平台是否正规...
矅光智策APP平台违规经营非法...   矅光智策APP对外宣称是“商城订购”“现货交易”,但查询其经营范围,并未显示具备开展现货期货交易...
黄金珠宝怎么选?内侧刻字都代表... 潮新闻客户端 记者 马焱 通讯员 任倩影 9月8日下午,“云游杭州 乐购金秋”——“浙城·浙放心”活...
原创 冰... 最近全球国债市场正在上演魔幻一幕: 美债、日债、欧债遭遇猛烈抛售,收益率冲到几十年新高,美国财政部都...
日韩股市开盘表现分化 上证报中国证券网讯 9月9日,日韩股市开盘表现分化,韩国综合指数开盘上涨0.26%,报6972.87...