当前位置: 代码迷 >> Android >> Android 编纂多线程代码常用接口及官方注释
  详细解决方案

Android 编纂多线程代码常用接口及官方注释

热度:46   发布时间:2016-04-28 05:29:12.0
Android 编写多线程代码常用接口及官方注释

在编写多线程代码时常会接触到一些接口,这些接口是专门为多线程编程设计的。本文将总结这些常用的接口,如果大家发现其它的,希望能补充一下。以后我将详细介绍在JDK中每种接口的实现和用法。

1、无参数,无返回值,无异常:Runnable

/** * Represents a command that can be executed. Often used to run code in a * different [email protected] Thread}. */public interface Runnable {    /**     * Starts executing the active part of the class' code. This method is     * called when a thread is started that has been created with a class which     * implements [email protected] Runnable}.     */    public void run();}

2、无参数,有返回值,有异常:Callable

/** * A task that returns a result and may throw an exception. * Implementors define a single method with no arguments called * [email protected] call}. * * <p>The [email protected] Callable} interface is similar to [email protected] * java.lang.Runnable}, in that both are designed for classes whose * instances are potentially executed by another thread.  A * [email protected] Runnable}, however, does not return a result and cannot * throw a checked exception. * * <p>The [email protected] Executors} class contains utility methods to * convert from other common forms to [email protected] Callable} classes. * * @see Executor * @since 1.5 * @author Doug Lea * @param <V> the result type of method [email protected] call} */public interface Callable<V> {    /**     * Computes a result, or throws an exception if unable to do so.     *     * @return computed result     * @throws Exception if unable to compute a result     */    V call() throws Exception;}

3、将线程的提交与其运行机制(使用、调度等)解耦合者:Executor

/** * An object that executes submitted [email protected] Runnable} tasks. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, etc.  An [email protected] Executor} is normally used * instead of explicitly creating threads. For example, rather than * invoking [email protected] new Thread(new(RunnableTask())).start()} for each * of a set of tasks, you might use: * * <pre> * Executor executor = <em>anExecutor</em>; * executor.execute(new RunnableTask1()); * executor.execute(new RunnableTask2()); * ... * </pre> * * However, the [email protected] Executor} interface does not strictly * require that execution be asynchronous. In the simplest case, an * executor can run the submitted task immediately in the caller's * thread: * *  <pre> [email protected] * class DirectExecutor implements Executor { *   public void execute(Runnable r) { *     r.run(); *   } * }}</pre> * * More typically, tasks are executed in some thread other * than the caller's thread.  The executor below spawns a new thread * for each task. * *  <pre> [email protected] * class ThreadPerTaskExecutor implements Executor { *   public void execute(Runnable r) { *     new Thread(r).start(); *   } * }}</pre> * * Many [email protected] Executor} implementations impose some sort of * limitation on how and when tasks are scheduled.  The executor below * serializes the submission of tasks to a second executor, * illustrating a composite executor. * *  <pre> [email protected] * class SerialExecutor implements Executor { *   final Queue<Runnable> tasks = new ArrayDeque<Runnable>(); *   final Executor executor; *   Runnable active; * *   SerialExecutor(Executor executor) { *     this.executor = executor; *   } * *   public synchronized void execute(final Runnable r) { *     tasks.offer(new Runnable() { *       public void run() { *         try { *           r.run(); *         } finally { *           scheduleNext(); *         } *       } *     }); *     if (active == null) { *       scheduleNext(); *     } *   } * *   protected synchronized void scheduleNext() { *     if ((active = tasks.poll()) != null) { *       executor.execute(active); *     } *   } * }}</pre> * * The [email protected] Executor} implementations provided in this package * implement [email protected] ExecutorService}, which is a more extensive * interface.  The [email protected] ThreadPoolExecutor} class provides an * extensible thread pool implementation. The [email protected] Executors} class * provides convenient factory methods for these Executors. * * <p>Memory consistency effects: Actions in a thread prior to * submitting a [email protected] Runnable} object to an [email protected] Executor} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * its execution begins, perhaps in another thread. * * @since 1.5 * @author Doug Lea */public interface Executor {    /**     * Executes the given command at some time in the future.  The command     * may execute in a new thread, in a pooled thread, or in the calling     * thread, at the discretion of the [email protected] Executor} implementation.     *     * @param command the runnable task     * @throws RejectedExecutionException if this task cannot be     * accepted for execution     * @throws NullPointerException if command is null     */    void execute(Runnable command);}
4、检查线程的运行状态,获取线程的运行结果:Feature

Future接口是Java线程Future模式的实现,可以来进行异步计算。
Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。
Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时的方法就是实现Java程序执行超时的关键。

/** * A [email protected] 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 * [email protected] get} when the computation has completed, blocking if * necessary until it is ready.  Cancellation is performed by the * [email protected] 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 [email protected] Future} for the sake * of cancellability but not provide a usable result, you can * declare types of the form [email protected] Future<?>} and * return [email protected] null} as a result of the underlying task. * * <p> * <b>Sample Usage</b> (Note that the following classes are all * made-up.) <p> *  <pre> [email protected] * interface ArchiveSearcher { String search(String target); } * class App { *   ExecutorService executor = ... *   ArchiveSearcher searcher = ... *   void showSearch(final String target) *       throws InterruptedException { *     Future<String> future *       = executor.submit(new Callable<String>() { *         public String call() { *             return searcher.search(target); *         }}); *     displayOtherThings(); // do other things while searching *     try { *       displayText(future.get()); // use future *     } catch (ExecutionException ex) { cleanup(); return; } *   } * }}</pre> * * The [email protected] FutureTask} class is an implementation of [email protected] Future} that * implements [email protected] Runnable}, and so may be executed by an [email protected] Executor}. * For example, the above construction with [email protected] submit} could be replaced by: *  <pre> [email protected] * FutureTask<String> future = *   new FutureTask<String>(new Callable<String>() { *     public String call() { *       return searcher.search(target); *   }}); * executor.execute(future);}</pre> * * <p>Memory consistency effects: Actions taken by the asynchronous computation * <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a> * actions following the corresponding [email protected] Future.get()} in another thread. * * @see FutureTask * @see Executor * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this Future's [email protected] get} method */public interface Future<V> {    /**     * Attempts to cancel execution of this task.  This attempt will     * fail if the task has already completed, has already been cancelled,     * or could not be cancelled for some other reason. If successful,     * and this task has not started when [email protected] cancel} is called,     * this task should never run.  If the task has already started,     * then the [email protected] mayInterruptIfRunning} parameter determines     * whether the thread executing this task should be interrupted in     * an attempt to stop the task.     *     * <p>After this method returns, subsequent calls to [email protected] #isDone} will     * always return [email protected] true}.  Subsequent calls to [email protected] #isCancelled}     * will always return [email protected] true} if this method returned [email protected] true}.     *     * @param mayInterruptIfRunning [email protected] true} if the thread executing this     * task should be interrupted; otherwise, in-progress tasks are allowed     * to complete     * @return [email protected] false} if the task could not be cancelled,     * typically because it has already completed normally;     * [email protected] true} otherwise     */    boolean cancel(boolean mayInterruptIfRunning);    /**     * Returns [email protected] true} if this task was cancelled before it completed     * normally.     *     * @return [email protected] true} if this task was cancelled before it completed     */    boolean isCancelled();    /**     * Returns [email protected] true} if this task completed.     *     * Completion may be due to normal termination, an exception, or     * cancellation -- in all of these cases, this method will return     * [email protected] true}.     *     * @return [email protected] true} if this task completed     */    boolean isDone();    /**     * Waits if necessary for the computation to complete, and then     * retrieves its result.     *     * @return the computed result     * @throws CancellationException if the computation was cancelled     * @throws ExecutionException if the computation threw an     * exception     * @throws InterruptedException if the current thread was interrupted     * while waiting     */    V get() throws InterruptedException, ExecutionException;    /**     * Waits if necessary for at most the given time for the computation     * to complete, and then retrieves its result, if available.     *     * @param timeout the maximum time to wait     * @param unit the time unit of the timeout argument     * @return the computed result     * @throws CancellationException if the computation was cancelled     * @throws ExecutionException if the computation threw an     * exception     * @throws InterruptedException if the current thread was interrupted     * while waiting     * @throws TimeoutException if the wait timed out     */    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

5、RunnableFuture

/** * A [email protected] Future} that is [email protected] Runnable}. Successful execution of * the [email protected] run} method causes completion of the [email protected] Future} * and allows access to its results. * @see FutureTask * @see Executor * @since 1.6 * @author Doug Lea * @param <V> The result type returned by this Future's [email protected] get} method */public interface RunnableFuture<V> extends Runnable, Future<V> {    /**     * Sets this Future to the result of its computation     * unless it has been cancelled.     */    void run();}


  相关解决方案