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. server环境信息【C#代码获取】

    server环境信息[C#代码获取] public class ServicesMessage { [DllImport("kernel32", CharSet = CharSet ...

  2. scaleType-模拟按钮加文字整天点击效果

    经常碰到这种情况,就是一个按钮下面有文字,我们点击按钮的时候,按钮跟文字的背景都是同时变化的.我们看下下面的效果 点击以后如下 如果想要实现这个方法,网上有很多的方法,主要就是自定义控件,或者是使用t ...

  3. Android 给图片 加边框

    图片处理时,有时需要为图片加一些边框,下面介绍一种为图片添加简单边框的方法. 基本思路是:将边框图片裁剪成八张小图片(图片大小最好一致,不然后面处理会很麻烦),分别对应左上角,左边,左下角,下边,右下 ...

  4. RTSP、HTTP、HTTPS、SDP四种协议详解

    我们将主要讲解RTSP,HTTP,HTTPS, SDP四种协议.  一:RTSP协议简介 实时流协议RTSP是一个应用层协议,用于控制具有实时特性的数据(例如多媒体流)的传送. RTSP协议一般与RT ...

  5. 26.使用IntelliJ IDEA开发Java Web项目时,修改了JSP后刷新浏览器无法及时显示修改后的页面

    转自:https://blog.csdn.net/yuxxz/article/details/51318908 使用IntelliJ IDEA开发Java Web项目时,修改了JSP后刷新浏览器无法及 ...

  6. BZOJ5027: 数学题

    Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 140  Solved: 48[Submit][Status][Discuss] Description ...

  7. VS中创建自定义一个VC工程为基础的开发向导的总结

    作者:朱金灿 来源:http://blog.csdn.net/clever101 VS允许用户进行自定义开发向导.自定义开发向导的好处在于将常用的设置都通过向导生成,从而大大提供开发效率.特别是在开发 ...

  8. HttpWebRequest使用证书请求

    HttpWebRequest使用证书请求 //是否使用证书                if (isUseCert)                {                    stri ...

  9. javafx clipboard

    public class EffectTest extends Application { public static void main(String[] args) { launch(args); ...

  10. px、em、rem、vw、vh、vm、rpx这些单位的

    px是像素 em是参考父元素的font-size的倍数 rem是参考根元素的font-size 常用于响应式,一般会让html的font-size:625%,body的大小为.16rem.这样1rem ...