Java 中的 Callable 对象详解

来源:互联网 发布:雅马哈f310与f600 知乎 编辑:程序博客网 时间:2024/06/05 00:28
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表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。

关于Future对象:

public interface Future<V>

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task. 

运用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...

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

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

关于Executors、ExecutorService(线程池)对象:

public class Executors
extends Object

Factory and utility methods for Executor, ExecutorService,ScheduledExecutorService,ThreadFactory, and Callable classes defined in this package. 

static ExecutorService newSingleThreadExecutor()         

   Creates an Executor that uses a single worker thread operating off an unbounded queue.

newSingleThreadExecutor:
创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。(注意,如果因为在关闭前的执行期间出现失败而终止了此单个线程,那么如果需要,一个新线程将代替它执行后续的任务)。可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的。与其他等效的 newFixedThreadPool(1) 不同,可保证无需重新配置此方法所返回的执行程序即可使用其他的线程。
-单例线程,任意时间池中只能有一个线程 
-用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE)

public interface ExecutorService
extends Executor

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to stop accepting new tasks. After being shut down, the executor will eventually terminate, at which point no tasks are actively executing, no tasks are awaiting execution, and no new tasks can be submitted.

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.) 

译:Executor 提供了管理终止的方法,以及可为跟踪一个或多个异步任务执行状况而生成 Future 的方法。

可以关闭 ExecutorService,这将导致其拒绝新任务。提供两个方法来关闭 ExecutorServiceshutdown() 方法在终止前允许执行以前提交的任务,而shutdownNow() 方法阻止等待任务启动并试图停止当前正在执行的任务。在终止时,执行程序没有任务在执行,也没有任务在等待执行,并且无法提交新任务。应该关闭未使用的ExecutorService 以允许回收其资源。

通过创建并返回一个可用于取消执行和/或等待完成的 Future,方法 submit 扩展了基本方法 Executor.execute(java.lang.Runnable)。方法 invokeAnyinvokeAll 是批量执行的最常用形式,它们执行任务 collection,然后等待至少一个,或全部任务完成(可使用ExecutorCompletionService 类来编写这些方法的自定义变体)。


<T> Future<T>submit(Callable<T> task)
          Submits a value-returning task for execution and returns a Future representing the pending results of the task.


Executor对象,详见API文档:java.util.concurrent 接口 Executor

3 0
原创粉丝点击