Java Concurrency - Callable & Future
One of the advantages of the Executor framework is that you can run concurrent tasks that return a result. The Java Concurrency API achieves this with the following two interfaces:
- Callable: This interface is similar to the Runnable interface. It has the call() method which you have to implement the logic of a task. The Callable interface is a parameterized interface, meaning you have to indicate the type of data the call() method will return.
- Future: This interface has some methods to obtain the result generated by a Callable object and to manage its state.
/**
* This class calculates if a number is a prime number.
* It can be executed in an executor because it implements the Callable interface.
* The call() method will return a String
*/
public class PrimesCalculator implements Callable<String> { private int num; public PrimesCalculator(int num) {
this.num = num;
} /**
* Method called by the executor to execute this task
* and calculate if a number is a prime number
*/
@Override
public String call() throws Exception {
String msg = Primes.isPrime(num) ? String.format("%d is a prime number.", num)
: String.format("%d is not a prime number.", num);
TimeUnit.SECONDS.sleep(new Random().nextInt(3));
return msg;
}
} public class Main { /**
* @param args
*/
public static void main(String[] args) { // Create a ThreadPoolExecutor with fixed size. It has a maximun of two threads
ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors.newFixedThreadPool(2);
// List to store the Future objects that control the execution of the task and
// are used to obtain the results
List<Future<Integer>> resultList=new ArrayList<>(); // Create a random number generator
Random random=new Random();
// Create and send to the executor the ten tasks
for (int i=0; i<10; i++){
Integer number=new Integer(random.nextInt(10));
FactorialCalculator calculator=new FactorialCalculator(number);
Future<Integer> result=executor.submit(calculator);
resultList.add(result);
} // Wait for the finalization of the ten tasks
do {
System.out.printf("Main: Number of Completed Tasks: %d\n",executor.getCompletedTaskCount());
for (int i=0; i<resultList.size(); i++) {
Future<Integer> result=resultList.get(i);
System.out.printf("Main: Task %d: %s\n",i,result.isDone());
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (executor.getCompletedTaskCount()<resultList.size()); // Write the results
System.out.printf("Main: Results\n");
for (int i=0; i<resultList.size(); i++) {
Future<Integer> result=resultList.get(i);
Integer number=null;
try {
number=result.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.printf("Core: Task %d: %d\n",i,number);
} // Shutdown the executor
executor.shutdown(); } }
In this case, you have learned how to use the Callable interface to launch concurrent tasks that return a result. You have implemented the PrimesCalculator class that implements the Callable interface with String as the type of the result. Hence, it returns before type of the call() method.
The other critical point of this example is in the Main class. You send a Callable object to be executed in an executor using the submit() method. This method receives a Callable object as a parameter and returns a Future object that you can use with two main objectives:
- You can control the status of the task: you can cancel the task and check if it has finished. For this purpose, you have used the isDone() method to check if the tasks had finished.
- You can get the result returned by the call() method. For this purpose, you have used the get() method. This method waits until the Callable object has finished the execution of the call() method and has returned its result. If the thread is interrupted while the get() method is waiting for the result, it throws an InterruptedException exception. If the call() method throws an exception, this method throws an ExecutionException exception.
When you call the get() method of a Future object and the task controlled by this object hasn't finished yet, the method blocks until the task finishes. The Future interface provides another version of the get() method.
- get(long timeout, TimeUnit unit): This version of the get method, if the result of the task isn't available, waits for it for the specified time. If the specified period of time passes and the result isn't yet available, the method returns a null value. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.
Java Concurrency - Callable & Future的更多相关文章
- Java - 多线程Callable、Executors、Future
http://blog.csdn.net/pipisorry/article/details/44341579 Introduction Callable接口代表一段能够调用并返回结果的代码; Fut ...
- 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 并发编程——Callable+Future+FutureTask
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- java并发--Callable、Future和FutureTask
在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需要获取执行结果,就 ...
- Java多线程 - Callable和Future
已知的创建多线程的方法有继承Tread类和实现Runnable方法.此外Java还提供了Callable接口,Callable接口也提供了一个call()方法来做为线程执行体.但是call()方法与r ...
- java 并发runable,callable,future,futureTask
转载自:http://www.cnblogs.com/dolphin0520/p/3949310.html package future_call; import java.util.concurre ...
- Java多线程Callable和Future类详解
public interface Callable<V> 返回结果并且可能抛出异常的任务.实现者定义了一个不带任何参数的叫做 call 的方法 public in ...
- Java并发编程:ThreadPoolExecutor + Callable + Future(FutureTask) 探知线程的执行状况
如题 (总结要点) 使用ThreadPoolExecutor来创建线程,使用Callable + Future 来执行并探知线程执行情况: V get (long timeout, TimeUnit ...
- Java线程池(Callable+Future模式)
转: Java线程池(Callable+Future模式) Java线程池(Callable+Future模式) Java通过Executors提供四种线程池 1)newCachedThreadPoo ...
随机推荐
- mysql的interval函数用法
Name: 'INTERVAL' Description: Syntax: INTERVAL(N,N1,N2,N3,...) Returns 0 if N < N1, 1 if N < N ...
- 下载Xml文件方法
#region 下载Xml文件方法 //定义委托 private delegate void DownLoadDelegate(string url, string filename); privat ...
- [前端JS学习笔记]JavaScript CallBack
一.概念介绍 CallBack : "回调" . 在spring优秀框架回调无处不在, 回调的运用场景很多, 如 swt事件监听.netty等.它的主要作用是提高程序执行效率, 一 ...
- Centos 6.5安装python3.5.1
查看python的版本 #python -V Python 2.6.6 1.下载Python-3.5.1 #wget https://www.python.org/ftp/python/3.5.1/ ...
- HTML输出 二 控制行背景颜色
$Infors = Get-Content ports01.txt$Temp_PortStatustxt = "C:\Windows\Temp\PortStatustxt.txt" ...
- Ping批量函数
function pingm ($file){ $ips = gc $file foreach ($ip in $ips) { $cmdline +="ping " + $ip + ...
- 【Cocos2d-x】 HttpClient 网络通信(Http)的简单应用
Cocos2dx 为我们封装了在cocos2dx中http的网络框架,其文件在cocos2dx引擎包的extensions\network文件下的 HttpClient.HttpRequest .Ht ...
- Codeforces gym 100685 C. Cinderella 水题
C. CinderellaTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100685/problem/C ...
- 也谈读书和书籍选择问题(C#)
前言 读到一篇.net程序员应该看什么书?深有感触.以前曾经用C#也开发过几年的东西.在那里对相关语言和开发都有了一定的了解.这里,结合自己当初的一些体会和见识把一些比较好的书籍也和大家分享一下.这一 ...
- Cocos2d-x多语言支持解决方式
很多其它相关内容请查看本人博客:http://www.bokeyi.com/ll/category/cocos2d-x/ 利用.plist文件让Cocos2d-x轻松支持多语言. .plist文件类似 ...