Sometime back I wrote a post about Java Callable Future interfaces that we can use to get the concurrent processing benefits of threads as well as they are capable of returning value to the calling program.

FutureTask is base concrete implementation of Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled. We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously.

Let’s see the example of FutureTask with a simple program.

Since FutureTask requires a callable object, we will create a simple Callable implementation.


Copy
package com.journaldev.threads; import java.util.concurrent.Callable; public class MyCallable implements Callable<String> {
<span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> waitTime;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyCallable</span><span class="hljs-params">(<span class="hljs-keyword">int</span> timeInMillis)</span></span>{
<span class="hljs-keyword">this</span>.waitTime=timeInMillis;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">call</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
Thread.sleep(waitTime);
<span class="hljs-comment">//return the thread name executing this callable task</span>
<span class="hljs-keyword">return</span> Thread.currentThread().getName();
}

}

Here is an example of FutureTask method and it’s showing commonly used methods of FutureTask.


Copy
package com.journaldev.threads; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; public class FutureTaskExample { public static void main(String[] args) {
MyCallable callable1 = new MyCallable(1000);
MyCallable callable2 = new MyCallable(2000); FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
FutureTask<String> futureTask2 = new FutureTask<String>(callable2); ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(futureTask1);
executor.execute(futureTask2); while (true) {
try {
if(futureTask1.isDone() && futureTask2.isDone()){
System.out.println("Done");
//shut down executor service
executor.shutdown();
return;
} if(!futureTask1.isDone()){
//wait indefinitely for future task to complete
System.out.println("FutureTask1 output="+futureTask1.get());
} System.out.println("Waiting for FutureTask2 to complete");
String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
if(s !=null){
System.out.println("FutureTask2 output="+s);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}catch(TimeoutException e){
//do nothing
}
} } }

When we run above program, you will notice that it doesn’t print anything for sometime because get() method of FutureTask waits for the task to get completed and then returns the output object. There is an overloaded method also to wait for only specified amount of time and we are using it for futureTask2. Also notice the use of isDone() method to make sure program gets terminated once all the tasks are executed.

Output of above program will be:


Copy
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
FutureTask2 output=pool-1-thread-2
Done

As such there is no benefit of FutureTask but it comes handy when we want to override some of Future interface methods and don’t want to implement every method of Future interface.



About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

Java FutureTask Example Program(Java FutureTask例子)的更多相关文章

  1. Java 并发编程——Callable+Future+FutureTask

    Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...

  2. Java 线程池Future和FutureTask

    Future表示一个任务的周期,并提供了相应的方法来判断是否已经完成或者取消,以及获取任务的结果和取消任务. Future接口源码: public interface Future<V> ...

  3. Java并发案例04---Future和 FutureTask

    4.Future和 FutureTask 4.1 Future是Callable的返回结果. 它有三个功能 1.判断任务是否完成 2.能够中断任务 3.能够获取任务返回结果 4.2 FutureTas ...

  4. Java Callable Future Example(java 关于Callable,Future的例子)

    Home » Java » Java Callable Future Example Java Callable Future Example April 3, 2018 by Pankaj 25 C ...

  5. Java 守护线程(Daemon) 例子

    当我们在Java中创建一个线程,缺省状态下它是一个User线程,如果该线程运行,JVM不会终结该程序.当一个线被标记为守护线程,JVM不会等待其结束,只要所有用户(User)线程都结束,JVM将终结程 ...

  6. [20160701]DevideByZeroWithoutNoException——from 《Java How To Program (Early Objects), 10th》

    //一段优美的例子 import java.util.Scanner; import java.util.InputMismatchException; public class DevideByZe ...

  7. java 多线程——quartz 定时调度的例子

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

  8. java 多线程——一个定时调度的例子

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

  9. java连接mysql的一个小例子

    想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径 在eclipse中,Project的properties里面的java build path里面添加引用 连接成功的一 ...

随机推荐

  1. LintCode 二叉树的遍历 (非递归)

    前序: class Solution { public: /** * @param root: The root of binary tree. * @return: Preorder in vect ...

  2. [转]C语言字节对齐问题详解

    C语言字节对齐问题详解 转载:https://www.cnblogs.com/clover-toeic/p/3853132.html 引言 考虑下面的结构体定义: typedef struct{ ch ...

  3. Razor数组数据

    控制器层 public ActionResult DemoArray() { Product[] array = { new Product {Name = "Kayak", Pr ...

  4. 智课雅思词汇---二、词根acu和acr

    智课雅思词汇---二.词根acu和acr 一.总结 一句话总结:acu和acr:sharp锋利的,敏捷的: acuteacutelyacuity sharp锋利的,敏捷的 1.词根acr表示什么意思? ...

  5. Inception V3 的 tensorflow 实现

    tensorflow 官方给出的实现:models/inception_v3.py at master · tensorflow/models · GitHub 1. 模型结构 首先来看 Incept ...

  6. 83.const与类

    const常量对象,无法改变数据,只能引用尾部带const方法 类的成员如果是const,可以默认初始化,也可以构造的初始化,不可在构造函数内部初始化 类中的const成员,无法直接修改,可以间接修改 ...

  7. Codefroces Round #429Div2 (A,B,C)

    A. Generous Kefa time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  8. spark源码编译,本地调试

    1.下载源码 2.进入源码根据README.md编译源码,注意使用的是源码目录下的maven编译 3.用idea导入顶层pom文件 4.修改顶层pom文件和example下的pom文件,将scope的 ...

  9. Django模型三

    关联对象操作及多表查询 关联表的数据操作: 一对多: 正向:如果一个模型有外键字段,通过这个模型对外键进行操作叫做正向. 更新: 通过属性赋值 In [1]: from teacher.models ...

  10. 【2017 Multi-University Training Contest - Team 5】Rikka with Subset

    [Link]: [Description] 给你a数组的n个数的所有2^n个子集的2^n个子集元素的和; 子集元素的和最大为m; 告诉你各个子集元素的和出现的次数; 如 1 2 则0出现1次,1出现1 ...