项目中经常有些任务需要异步(提交到线程池中)去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢?用runnable是无法实现的,我们需要用callable实现。

FutureTask 也可以做闭锁,它是 Future 和 callable 的结合体。所以我们有必要来了解 FutureTask 这个类。

FutureTask 的继承关系类图

先看 FutureTask 类的继承:

public class FutureTask<V> implements RunnableFuture<V> 

它继承自 RunnableFuture,可以看出他是 Runnable 和 Future 的结合体。

public interface RunnableFuture<V> extends Runnable, Future<V> { /**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}

我们熟悉的 Runnable 接口:

public interface Runnable {
public abstract void run();
}

不常见的Future 接口,用来获取异步计算结果:

public interface Future<V> { /**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, has already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when {@code cancel} is called,
* this task should never run. If the task has already started,
* then the {@code mayInterruptIfRunning} parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*/
boolean cancel(boolean mayInterruptIfRunning); /**
* Returns {@code true} if this task was cancelled before it completed
* normally.
*/
boolean isCancelled();//如果任务被取消,返回true /**
* Returns {@code true} if this task completed.
*/
boolean isDone();//如果任务执行结束,无论是正常结束或是中途取消还是发生异常,都返回true。 /**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*/
V get() throws InterruptedException, ExecutionException; //获取异步执行的结果,如果没有结果可用,此方法会阻塞直到异步计算完成。 /**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*/
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}

到这里,FutureTask 整个继承关系已经很清楚了。为了更直观一点,我用 starUML 画出它的类继承关系图。

在类关系图中,我们可以看到 FutureTask 的构造函数,包含了之前没有见过的类型:Callable。我们直接看下它的两个构造函数实现,进一步了解看看:

//构造函数1
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
//构造函数2
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}

这里已经非常清楚了,最终都是赋值给 FutureTask 的内部变量 callable。它是一个接口,包含一个有返回值的函数 call()。

public interface Callable<V> { /**
* 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;
}

通过上面的讲解,我们已经知道 Future,FutureTask,Callable,Runnable的关系了。那么,说了这么多主要是想干嘛呢?

没错,主要就是为了线程执行完成后能够返回结果。我们知道,Runnable 接口执行完成后,是没法返回结果的。所以,我们如果想要能够返回执行的结果,必须使用 callable 接口。

应用场景

比如我们有个耗时的计算操作,现在创建一个子线程执行计算操作,主线程通过 FutureTask.get() 的方式获取计算结果,如果计算还没有完成,则会阻塞一直等到计算完成。

下面我们直接编写代码来实现上面的应用场景。
使用 Callable + FutureTask 获取执行结果:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; public class FutureTaskTest {
// 创建一个Future对象,并把Callable的实现传给构造函数
private static final FutureTask<Integer> future = new FutureTask<Integer>(new CallableTest()); public static void main(String[] args) {
// 创建一个线程
final Thread thread = new Thread(future);
// 启动线程
thread.start();
try {
Thread.sleep(1000);
System.out.println("Main thread is running");
// 获取计算结果,会阻塞知道计算完毕
System.out.println("get the sub thread compute result : " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("main thread is end");
} // 实现Callable接口,耗时操作
static class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int ret = 0;
Thread.sleep(1000);
System.out.println("sub thread is computing");
for (int i = 0; i < 1000; i++) {
ret += i;
}
System.out.println("sub thread is finish compute");
return ret;
}
}
}

运行结果:

另外一种方式,是使用 Callable + Future + ExecutorService 的方式。ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期。

在ExecutorService接口中声明了若干个submit方法的重载版本:

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

第一个submit方法里面的参数类型就是Callable。

示例如下:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask; public class FutureTaskTest {
public static void main(String[] args) {
// 返回一个线程池,通常都和这种线程宽架搭配
ExecutorService threadPool = Executors.newSingleThreadExecutor();
System.out.println("Main thread is running");
// 提交给线程,返回一个Future类,并执行
Future<Integer> future = threadPool.submit(new CallableTest());
try {
Thread.sleep(1000);
// 获取计算结果,会阻塞知道计算完毕
System.out.println("get the sub thread compute result : " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("main thread is end");
} // 实现Callable接口,耗时操作
static class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int ret = 0;
Thread.sleep(1000);
System.out.println("sub thread is computing");
for (int i = 0; i < 1000; i++) {
ret += i;
}
System.out.println("sub thread is finish compute");
return ret;
}
}
}

执行结果:

转自:https://blog.csdn.net/amd123456789/article/details/80522855

并发编程-Future+callable+FutureTask 闭锁机制的更多相关文章

  1. Java并发编程:Callable、Future和FutureTask

    作者:海子 出处:http://www.cnblogs.com/dolphin0520/ 本博客中未标明转载的文章归作者海子和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置 ...

  2. (转)Java并发编程:Callable、Future和FutureTask

    Java并发编程:Callable.Future和FutureTask 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一 ...

  3. Java并发编程:Callable、Future和FutureTask(转)

    Java并发编程:Callable.Future和FutureTask 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一 ...

  4. 15、Java并发编程:Callable、Future和FutureTask

    Java并发编程:Callable.Future和FutureTask 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一 ...

  5. 007 Java并发编程:Callable、Future和FutureTask

    原文https://www.cnblogs.com/dolphin0520/p/3949310.html Java并发编程:Callable.Future和FutureTask 在前面的文章中我们讲述 ...

  6. 并发编程 05—— Callable和Future

    Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...

  7. Java并发编程:Callable、Future和FutureTask的实现

    启动线程执行任务,如果需要在任务执行完毕之后得到任务执行结果,可以使用从Java 1.5开始提供的Callable和Future 下面就分析一下Callable.Future以及FutureTask的 ...

  8. [转载] Java并发编程:Callable、Future和FutureTask

    转载自http://www.cnblogs.com/dolphin0520/p/3949310.html 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Run ...

  9. 【Java并发编程】Callable、Future和FutureTask的实现

    启动线程执行任务,如果需要在任务执行完毕之后得到任务执行结果,可以使用从Java 1.5开始提供的Callable和Future 下面就分析一下Callable.Future以及FutureTask的 ...

随机推荐

  1. 华为开发者论坛FusionStage版块

    FusionStage版块 http://developer.huawei.com/ict/forum/forum.php?mod=forumdisplay&fid=400191&pa ...

  2. 【转载】MySQL和Keepalived高可用双主复制

    服务器主机IP和虚拟浮动IP配置 RealServer A 192.168.75.133 RealServer B 192.168.75.134 VIP A 192.168.75.110 VIP B ...

  3. 多线程Parallel和Task

    不管是Parallel还是Task,最里面都是线程池(里面是线程)当开启多个任务后,系统会根据当前的线程池的资源进行分配,任务则进行等待Parallel可以对系统的CPU进行设置,可以最大程度上榨干系 ...

  4. 数据绑定(二)把控件作为Binding源

    原文:数据绑定(二)把控件作为Binding源 下面的代码把一个TextBox的Text属性关联在了Slider的Value属性上 <Window x:Class="WpfApplic ...

  5. liunx 常用操作命令

    1.复制粘贴命令:在一行的任何位置按下yy,y是yanked拷贝的意思,然后去想粘贴的位置按下p即可.p是粘贴的意思. 2.如果想复制3行的话,按下3yy,就复制3行,如果想复制多行的话,直接按数字可 ...

  6. delphi资源文件的使用

    delphi资源文件的使用 资源文件(*.res)通过编译指令 $R 关联, 譬如工程文件 Project1 中的 {$R *.res} 就是关联 Project1.res 资源文件, 我们直接写作 ...

  7. WPF 窗体边框处理

    一般做wpf窗口时都不会使用默认的标题栏等,会把他隐藏掉 此时设置以下属性 WindowStyle.AllowsTransparency.ResizeMode 中的两个或三个都能达到目的. 有一种场景 ...

  8. eclipse 插件编写(一)

    由于项目开发进程中有一些重复性的代码进行编写,没有任何业务逻辑,粘贴复制又很麻烦且容易出错,故想起做一个eclipse插件来满足一下自己的工作需要,同时记录一下,以供以后参考与共同学习.本文主要讲解一 ...

  9. 领域驱动设计(DDD)的实践经验分享之ORM的思考

    原文:领域驱动设计(DDD)的实践经验分享之ORM的思考 最近一直对DDD(Domain Driven Design)很感兴趣,于是去网上找了一些文章来看看,发现它确实是个好东西.于是我去买了两本关于 ...

  10. 程序跳过UAC研究及实现思路(两种方法,现在可能都不行了)

    网上很对跳过UAC资料都是说如果让UAC弹出窗体,并没有真正跳过弹窗,这里结合动态提权+计划任务实现真正意义上的跳过UAC弹窗,运行程序的时候可以不出现UAC窗体,并且程序还是以高权限运行. vist ...