首页 > 其他 > 详细

Java 中的 Callable 对象

时间:2014-02-12 13:33:31      阅读:325      评论:0      收藏:0      [点我收藏+]
public interface Callable<V>

A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

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.

The Executors(An object that executes submitted Runnable tasks) class contains utility(有多种用途的) methods to convert from other common forms to Callable classes. 

方法:

V call() throws Exception
Computes a result, or throws an exception if unable to do so.

返回:
computed result
抛出:
Exception - if unable to compute a result

下面来比较 Callable 和 Runnable 接口:

Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
Callable和Runnable有几点不同:  
(1)Callable规定的方法是call(),而Runnable规定的方法是run().
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。  
(3)call()方法可抛出异常,而run()方法是不能抛出异常的。
(4)运行Callable任务可拿到一个Future(Future represents the result of an asynchronous computation.)对象, Future表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。

运用Callable,如:

public class BatteryTask  implements Callable<Result>{
    private Context context;
    private Battery battery;
    
    public BatteryTask(Context context,Battery battery){
        this.context = context;
        this.battery = battery;
    }
    @Override
    public Result call() throws Exception {
        try{...return...

............

Callback<String> callback = BatteryAlarmReceiver.this;
ExecutorService service = Executors.newSingleThreadExecutor();
Future<String> future = null;
BatteryTask task = new BatteryTask(context);
future = service.submit(task);
String result = null;
if (null != future) {
    result = future.get();
}... ...


Java 中的 Callable 对象

原文:http://blog.csdn.net/itzyjr/article/details/19095063

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!