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的更多相关文章

  1. Java - 多线程Callable、Executors、Future

    http://blog.csdn.net/pipisorry/article/details/44341579 Introduction Callable接口代表一段能够调用并返回结果的代码; Fut ...

  2. Java Callable Future Example(java 关于Callable,Future的例子)

    Home » Java » Java Callable Future Example Java Callable Future Example April 3, 2018 by Pankaj 25 C ...

  3. Java 并发编程——Callable+Future+FutureTask

    Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...

  4. java并发--Callable、Future和FutureTask

    在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需要获取执行结果,就 ...

  5. Java多线程 - Callable和Future

    已知的创建多线程的方法有继承Tread类和实现Runnable方法.此外Java还提供了Callable接口,Callable接口也提供了一个call()方法来做为线程执行体.但是call()方法与r ...

  6. java 并发runable,callable,future,futureTask

    转载自:http://www.cnblogs.com/dolphin0520/p/3949310.html package future_call; import java.util.concurre ...

  7. Java多线程Callable和Future类详解

         public interface Callable<V>    返回结果并且可能抛出异常的任务.实现者定义了一个不带任何参数的叫做 call 的方法      public in ...

  8. Java并发编程:ThreadPoolExecutor + Callable + Future(FutureTask) 探知线程的执行状况

    如题 (总结要点) 使用ThreadPoolExecutor来创建线程,使用Callable + Future 来执行并探知线程执行情况: V get (long timeout, TimeUnit ...

  9. Java线程池(Callable+Future模式)

    转: Java线程池(Callable+Future模式) Java线程池(Callable+Future模式) Java通过Executors提供四种线程池 1)newCachedThreadPoo ...

随机推荐

  1. Linux命令之env:显示当前用户的环境变量

    Linux系统里的env命令可以显示当前用户的环境变量,还可以用来在指定环境变量下执行其他命令.下面来比较一下set,env和export命令的异同:set命令显示当前shell的变量,包括当前用户的 ...

  2. [转]directsound抓取麦克风PCM数据封装类

    网上有很多方法从麦克风读取PCM数据,不想一一举例.只是在这里发布一个我自己写的directsound的麦克风PCM数据采集类,通过它,可以很方便的利用directsound技术把麦克风的数据采集到, ...

  3. SpringMVC(四)

    好久没有来谢谢总结性的东西了,一直在赶项目进度,终于忙完了,今天就来说说项目过程中遇到的一些问题: 1.关于在使用@Param的用法,在前面也说过了一点,但是在实际使用中还遇到了一个问题.就是在Map ...

  4. MT4平台上mql4实现的基于macd指标的智能交易EA

    屌丝命苦,拼爹拼不过,拼后台没有,技术宅一枚,情商有问题,不会见人说人话见鬼说鬼话,所以在国庆熬着混着,工作也没啥大起色,想想就郁闷,难不成一辈子就只能这样了? 苦思冥想,想得一条路,那就是程序化交易 ...

  5. 剑指OFFER之链表中倒数第k个节点(九度OJ1517)

    题目描述: 输入一个链表,输出该链表中倒数第k个结点.(hint: 请务必使用链表.) 输入: 输入可能包含多个测试样例,输入以EOF结束.对于每个测试案例,输入的第一行为两个整数n和k(0<= ...

  6. Python3.5.2官方文档学习备忘录

    网址:https://docs.python.org/3/ 虽然学习官方文档有些耗时,不过看最原版的还是感觉好一点,原汁原味没有曲解没有省略. 从命令行向Python传递参数,运行:python - ...

  7. Codeforces Gym 100513M M. Variable Shadowing 暴力

    M. Variable Shadowing Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100513/ ...

  8. C# 图片保存到数据库和从数据库读取图片并显示

    图片保存到数据库的方法: public void imgToDB(string sql)        {   //参数sql中要求保存的imge变量名称为@images            //调 ...

  9. 前端框架Bootstrap

    前端框架Bootstrap http://www.bootcss.com/ Bootstrap 编码规范 http://codeguide.bootcss.com/

  10. ABAP 日期时间函数(转)

    转自:http://www.sapjx.com/abap-datetime-function.html 函数名称 (内页-点击名称可查看操作) 函数说明 备注 FIMA_DATE_CREATE RP_ ...