项目中经常有些任务需要异步(提交到线程池中)去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢?用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. [Unity3D]Unity3D叙利亚NGUI血液和技能的冷却效果

    ---------------------------------------------------------------------------------------------------- ...

  2. abp框架(aspnetboilerplate)扩展系统表

    以OrganizationUnit为例,进行扩展,加入IsUse属性 1.创建一个新类,比如ExtendedOrganizationUnit,继承OrganizationUnit public cla ...

  3. jquery评分星星

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...

  4. jquery模拟飞秋

    <!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> ...

  5. WPF MVVM+EF 增删改查 简单示例(一)

    实现了那些功能,先看看效果图: 项目工程目录: 接下来开始具体的步骤: 第一步:在VS中新建工程 第二步:使用NuGet 安装EntityFramework 第三步:使用NuGet 安装EntityF ...

  6. 对OO的封装了有了新的理解——希望是普通函数来写总体流程来统管类似的业务,但却又涉及具体操作的函数,仍然可以达到目的

    就是不厌其烦,把那个具体操作函数封装成虚函数,只需要返回它的结果就行.而总体流程根据这个结果继续进行处理,这样就能总体流程和虚函数两不误了.

  7. PopupWindow设置动画效果

    创建popupwindow的方法 Button menu; private void showPopupWindow() { //设置contentView float density = Densi ...

  8. delphi Stomp客户端连接 RabbitMQ(1)

    最近公司想上个消息推送系统,网上搜了很多,因公司主要产品是Delphi,我选择了开源的RabbitMQ,Erlang语言开发,天生并行. 代码下载地址:delphistomp下载地址 windows上 ...

  9. Python:Pandas学习

    import pandas as pd import numpy as np s = pd.Series([1, 3, 6, np.nan, 44, 1]) df= pd.DataFrame(np.r ...

  10. Qt 5.6 5.8 vs2015 编译静态库版本(有全部的截图)good

    安装Qt 去Qt官网下载Qt安装包  安装Qt和源码,一定要勾选source选项  添加bin到系统变量  工具 需要python3和 perl. vs2015 第三方工具,到官方下载安装  在命令行 ...