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里面添加引用 连接成功的一 ...
随机推荐
- CS224d lecture 9札记
欢迎转载.转载注明出处: http://blog.csdn.net/neighborhoodguo/article/details/47193885 近期几课的内容不是非常难.还有我的理解能力有所提高 ...
- 【Struts2】Struts2纯手工安装、配置以及Helloworld,以最新版struts 2.3.20 GA做样例
很多网上的教程对Struts2的配置.安装弄得不明不白,非常多高手以为小白是什么都懂.很多细节上面的地方没有说明清楚,甚至还有在Maven上面解说的,要知道Struts2跟Maven没有半点的关系.全 ...
- js---11闭包
//匿名立即调用函数 (function(){//把a,b,f全部隐藏在函数中,外部访问不到, var a = 5; var b = 6; function f(){ alert(a); } wind ...
- Android 学习笔记之Bitmap位图的旋转
位图的旋转也可以借助Matrix或者Canvas来实现. 通过postRotate方法设置旋转角度,然后用createBitmap方法创建一个经过旋转处理的Bitmap对象,最后用drawBitmap ...
- Python 面向对象与 C++、Java 的异同
1. 子类是否自动调用父类的构造方法 C++.Java 会在子类对象的构造中自动首先调用父类的构造: Python 则相对啰嗦一点: 如果子类不覆盖父类的__init__()方法,则子类默认将执行与父 ...
- 刘汝佳 算法竞赛-入门经典 第二部分 算法篇 第六章 2(Binary Trees)
112 - Tree Summing 题目大意:给出一个数,再给一颗树,每个头节点的子树被包含在头节点之后的括号里,寻找是否有从头节点到叶子的和与给出的数相等,如果有则输出yes,没有输出no! 解题 ...
- POJ 1991 DP
题意: 思路: 考虑DP 先把事件按照地点顺序排个序 f[i][j][0]表示从i到j还没有去过 现在在i f[i][j][1]表示从i到j还没有去过 现在在j 那么方程就呼之欲出了 f[i][j][ ...
- ajax的内容
ajax是什么? 通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新,可以局部刷新而不必整个页面整体刷新. url的简单认识: 进入服务器的三种方式: 1.localhost:端口号 ...
- LuoguP2765 魔术球问题(最大流)
题目描述 «问题描述: 假设有n根柱子,现要按下述规则在这n根柱子中依次放入编号为1,2,3,...的球. (1)每次只能在某根柱子的最上面放球. (2)在同一根柱子中,任何2个相邻球的编号之和为完全 ...
- Onsctl 配置ONS服务(10G)
Onsctl Onsctl这个命令是用来管理ONS(Oracle Notification Service)是OracleClustser实现FAN Event Push模型的基础. 在RAC环境下. ...