博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Callable/Future
阅读量:6232 次
发布时间:2019-06-21

本文共 3269 字,大约阅读时间需要 10 分钟。

hot3.png

 Callable,线程执行任务,它是jdk1.5加入到api中的,相比于Runnable,它有俩大优点:第一,它可以有返回值,且返回值由我们事先泛型的Callable<T>中的T决定。第二,当我们在执行一个任务时,如果超时,我们可以取消它的执行。

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

In last few posts, we learned a lot about  but sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

Callable interface use Generic to define the return type of Object.  class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.

Here is a simple example of Callable task that returns the name of thread executing the task after one second. We are using  to execute 100 tasks in parallel and use Future to get the result of the submitted tasks.

import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future; public class MyCallable implements Callable
{ @Override public String call() throws Exception { Thread.sleep(1000); //return the thread name executing this callable task return Thread.currentThread().getName(); } public static void main(String args[]){ //Get ExecutorService from Executors utility class, thread pool size is 10 ExecutorService executor = Executors.newFixedThreadPool(10); //create a list to hold the Future object associated with Callable List
> list = new ArrayList
>(); //Create MyCallable instance Callable
callable = new MyCallable(); for(int i=0; i< 100; i++){ //submit Callable tasks to be executed by thread pool Future
future = executor.submit(callable); //add Future to the list, we can get return value using Future list.add(future); } for(Future
fut : list){ try { //print the return value of Future, notice the output delay in console // because Future.get() waits for task to get completed System.out.println(new Date()+ "::"+fut.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } //shut down the executor service now executor.shutdown(); } }

转载于:https://my.oschina.net/u/138995/blog/177766

你可能感兴趣的文章
semat内核阿尔法的状态图
查看>>
5秒之后关闭广告
查看>>
spring-boot入门
查看>>
Oracle 11g AMM与ASMM切换
查看>>
jobtracker对提交作业的初始化
查看>>
虚拟机中安装完Lunix系统后,开机黑屏,只显示一个-,解决方法
查看>>
UVA458 The Decoder
查看>>
Qt编写OpenMP程序--双循环
查看>>
HDU2289:Cup(二分 + 数学)
查看>>
高并发计数器、红包、二维码使用如下
查看>>
洛谷 P1536 村村通(并查集)
查看>>
获取登录的IP或者信息
查看>>
selenium的那些事--运行报错
查看>>
hudson新建subversion项目的时候认证时弹出Authentication was not acknowledged
查看>>
[Reprint]C++函数前和函数后加const修饰符区别
查看>>
自定义博客园主题并添加各种小功能
查看>>
【转】控制不能离开finally子句主体
查看>>
ok 在博客园落户 安心做一个快乐的码农
查看>>
[Nhibernate]对象状态
查看>>
Python动态展现之一
查看>>