Java FutureTask Example Program(Java FutureTask例子)
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.
Java Priority Queue (PriorityQueue) Example
Java Generics Example Tutorial – Generic Method, Class, Interface
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.
About Pankaj
Java FutureTask Example Program(Java FutureTask例子)的更多相关文章
- Java 并发编程——Callable+Future+FutureTask
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- Java 线程池Future和FutureTask
Future表示一个任务的周期,并提供了相应的方法来判断是否已经完成或者取消,以及获取任务的结果和取消任务. Future接口源码: public interface Future<V> ...
- Java并发案例04---Future和 FutureTask
4.Future和 FutureTask 4.1 Future是Callable的返回结果. 它有三个功能 1.判断任务是否完成 2.能够中断任务 3.能够获取任务返回结果 4.2 FutureTas ...
- Java Callable Future Example(java 关于Callable,Future的例子)
Home » Java » Java Callable Future Example Java Callable Future Example April 3, 2018 by Pankaj 25 C ...
- Java 守护线程(Daemon) 例子
当我们在Java中创建一个线程,缺省状态下它是一个User线程,如果该线程运行,JVM不会终结该程序.当一个线被标记为守护线程,JVM不会等待其结束,只要所有用户(User)线程都结束,JVM将终结程 ...
- [20160701]DevideByZeroWithoutNoException——from 《Java How To Program (Early Objects), 10th》
//一段优美的例子 import java.util.Scanner; import java.util.InputMismatchException; public class DevideByZe ...
- java 多线程——quartz 定时调度的例子
java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...
- java 多线程——一个定时调度的例子
java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...
- java连接mysql的一个小例子
想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径 在eclipse中,Project的properties里面的java build path里面添加引用 连接成功的一 ...
随机推荐
- 用Shell脚本过滤Hadoop中不能訪问的节点
近期使用的一个集群hp1,由于维护集群的人不给力.节点总是过一段时间就掉一两个.今天发现重新启动hadoop时,HDFS已经进入保护模式了. 决定把slaves节点中的无法訪问的节点所有过滤掉.所以写 ...
- JavaScript提高:006:ASP.NET使用easyUI TABS标签updatepanel
前文使用了easyui的tab标签.切换问题,使用了session保存当前选中页,然后页面总体刷新时再切换至上次保存页码.那么使用updatepanel后,这个问题就非常好攻克了.http://blo ...
- 第一天,Mysql安装,DDL(数据库定义语言),DBA,DML(数据库操纵语言),导入外面的sql文件
把“D:\mysql-5.6.22-winx64\bin”添加到系统环境变量path中了,然后在任意目录可访问mysql等命令,这样如登录等操作就不需要进入MySQL安装目录才好执行! MySQL下载 ...
- Spark Tachyon的命令行使用
Tachyon命令行使用 Tachyon接口说明 接口操作示例 copyFromLocal copyToLocal ls和lsr count cat mkdir.rm.rmr和touch pin和un ...
- HTML5多维度数据分析
详情:http://echarts.baidu.com/index.html
- 【2017 Multi-University Training Contest - Team 4】Counting Divisors
[Link]:http://acm.hdu.edu.cn/showproblem.php?pid=6069 [Description] 定义d(i)为数字i的因子个数; 求∑rld(ik) 其中l,r ...
- 顶级、块级、内联,html元素的三大分类
学习html后, 你会了解一些基本的html元素(Element), 如p, h1~h6, br, div, li, ul, img等.如果将这些元素细分, 又可以分别归为顶级(top-level)元 ...
- Centos 6.8 安装 Protocol Buffers , v3.2.0有 BUG ,安装 3.1.0
Centos 6.8 安装 Protocol Buffers , v3.2.0有 BUG ,安装 3.1.0 切换到用户目录 cd ~ 安装 python2.7,须加入zlib wget http ...
- worktools-不同分辨率下图片移植
1.下载需要移植的平台代码 1)查看手机需要的项目平台信息:adb shell getprop | gerp flavor ----->mt6732_m561_p2_kangjia_cc ...
- JavaScript学习总结(3)——JavaScript函数(function)
一.函数基本概念 为完成某一功能的程序指令(语句)的集合,称为函数. 二.JavaScript函数的分类 1.自定义函数(我们自己编写的函数),如:function funName(){} 2.系统函 ...