Java 中的 Callable 对象

2014-11-24 02:45:22 · 作者: · 浏览: 0
public interface Callable
   
 
 

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(A Future represents the result of an asynchronous computation.)对象, Future表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。

运用Callable,如:

public class BatteryTask  implements Callable
  
   {
    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
  
    callback = BatteryAlarmReceiver.this;
ExecutorService service = Executors.newSingleThreadExecutor();
Future
   
     future = null; BatteryTask task = new BatteryTask(context); future = service.submit(task); String result = null; if (null != future) { result = future.get(); }... ...