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支持Emoji表情
让MySQL支持Emoji表情,涉及无线相关的 MySQL 数据库建议都提前采用 utf8mb4 字符集. utf8mb4和utf8到底有什么区别呢?原来以往的mysql的utf8一个字符最多3字节, ...
- rop框架签名功能控制
平台级控制: 通过<rop:annotation-driven/>的 sign-enable 属性即可开启或关闭服务平台签名验证功能:<rop:annotation-driven s ...
- Oracle-11g-R2(11.2.0.3.x)RAC Oracle Grid & Database 零宕机方式升级 PSU(自动模式)
升级环境: 1.源库版本: Grid Infrastructure:11.2.0.3.13 Database:11.2.0.3.13 2.目标库版本: Grid Infrastructure:11.2 ...
- C语言快排
C语言使用快排的方式有两种,1.直接用库函数stdlib.h里的qsort函数 2.自己编写快排代码(第一种方便,第二种较为自由) qsort 的函数原型是:void qsort(void*base, ...
- Sysprep命令详解
本主题描述了 Windows(R) 8 版本的系统准备 (Sysprep) 工具的命令行语法. 如果你打算创建安装映像以部署到不同的计算机上,则必须运行带有 /generalize 选项的 Syspr ...
- java 搭建webservice服务+testclient測试
整理别人的日志: 一.什么是webservice 一种构建应用程序的普遍模型,能够在不论什么支持网络通信的操作系统中执行.一种新的web应用程序分支,能够公布.定位通过web调用.它是一个应用组件,为 ...
- 瑞丽的SQL-基于窗体的排名计算
在SQL Server中,窗体被定义为用户指定的一组行. 之所以要提出窗体这个概念,由于这种基于窗体或分区的又一次计算在实际工作应用范围比較广泛.比如.假设我们要对每一个班级中的学生按成绩进行排序,在 ...
- Displaying Alerts with UIAlertView
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"You've ...
- POJ 1743 Musical Theme 后缀数组 最长重复不相交子串
Musical ThemeTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://poj.org/problem?id=1743 Description ...
- 算法:排序----Java选择排序
public static void selectionSort(int[] arr) { int len = arr.length; for (int i = 0; i < len; i++) ...