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. Android.mk脚本推断文件是否存在

    Android.mk 推断文件是否存在,若存在则复制该文件到某个文件夹 $(shell test -f [文件] && echo yes)的值假设是yes, 则文件存在,然后进行she ...

  2. Android 学习笔记之Bitmap位图的缩放

    位图的缩放也可以借助Matrix或者Canvas来实现. 通过postScale(0.5f, 0.3f)方法设置旋转角度,然后用createBitmap方法创建一个经过缩放处理的Bitmap对象,最后 ...

  3. elasticsearch index 之 Mapping

    Lucene索引的一个特点就filed,索引以field组合.这一特点为索引和搜索提供了很大的灵活性.elasticsearch则在Lucene的基础上更近一步,它可以是 no scheme.实现这一 ...

  4. 小白算法之路-非确定性多项式(non-deterministic polynomial,缩写NP)

    前端小白的算法之路   时隔多日终于解决了埋在心头的一道难题,霎时云开雾散,今天把一路而来碰到的疑惑和心得都记录下来,也算是开启了自己探索算法的大门. 问题背景 曾经有一个年少轻狂的职场小白,在前端圈 ...

  5. webservices 服务器未能识别 HTTP 头 SOAPAction 的值:.

    转自:https://blog.csdn.net/dxfasr/article/details/25029063 在用java发送给webservice服务器的时候报如下错误: AxisFault f ...

  6. OpenCV —— 摄像机模型与标定

    这种理论看的已经够多了,感觉应用价值不大(矫正畸变图像还凑合,用摄像机测距神马的...) 有始有终吧,简单把内容梳理一下 针孔  摄像机模型 —— 过于理想(不能为快速曝光收集足够的光线) 透镜可以聚 ...

  7. Gym 100952 H. Special Palindrome

    http://codeforces.com/gym/100952/problem/H H. Special Palindrome time limit per test 1 second memory ...

  8. log大全

    http://www.iconfont.cn/search/index?q=%E6%88%91%E7%9A%84&page=3

  9. WinForm无边框窗体移动方法

    C#WinForm无边框窗体移动方法.模仿鼠标单击标题栏移动窗体位置 这里介绍俩种办法 方法一:直接通过修改窗体位置从而达到移动窗体的效果 方法二:直接伪装发送单击任务栏消息,让应用程序误以为单击任务 ...

  10. 【2017 Multi-University Training Contest - Team 3】Kanade's sum

    [Link]:http://acm.hdu.edu.cn/showproblem.php?pid=6058 [Description] 给你n个数; 它们是由(1..n)组成的排列; 然后给你一个数字 ...