java多线程之Future和FutureTask使用实例

Executor框架使用Runnable 作为其基本的任务表示形式。Runnable是一种有局限性的抽象,然后可以写入日志,或者共享的数据结构,但是他不能返回一个值。

许多任务实际上都是存在延迟计算的:执行数据库查询,从网络上获取资源,或者某个复杂耗时的计算。对于这种任务,Callable是一个更好的抽象,他能返回一个值,并可能抛出一个异常。Future表示一个任务的周期,并提供了相应的方法来判断是否已经完成或者取消,以及获取任务的结果和取消任务。

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; }
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 <tt>cancel</tt> is called,
   * this task should never run. If the task has already started,
   * then the <tt>mayInterruptIfRunning</tt> 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 {@link #isDone} will
   * always return <tt>true</tt>. Subsequent calls to {@link #isCancelled}
   * will always return <tt>true</tt> if this method returned <tt>true</tt>.
   *
   * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
   * task should be interrupted; otherwise, in-progress tasks are allowed
   * to complete
   * @return <tt>false</tt> if the task could not be cancelled,
   * typically because it has already completed normally;
   * <tt>true</tt> otherwise
   */
  boolean cancel(boolean mayInterruptIfRunning);
 
  /**
   * Returns <tt>true</tt> if this task was cancelled before it completed
   * normally.
   *
   * @return <tt>true</tt> if this task was cancelled before it completed
   */
  boolean isCancelled();
 
  /**
   * Returns <tt>true</tt> if this task completed.
   *
   * Completion may be due to normal termination, an exception, or
   * cancellation -- in all of these cases, this method will return
   * <tt>true</tt>.
   *
   * @return <tt>true</tt> 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;
}

可以通过多种方法来创建一个Future来描述任务。ExecutorService中的submit方法接受一个Runnable或者Callable,然后返回一个Future来获得任务的执行结果或者取消任务。

 /**
   * Submits a value-returning task for execution and returns a
   * Future representing the pending results of the task. The
   * Future's <tt>get</tt> method will return the task's result upon
   * successful completion.
   *
   * <p>
   * If you would like to immediately block waiting
   * for a task, you can use constructions of the form
   * <tt>result = exec.submit(aCallable).get();</tt>
   *
   * <p> Note: The {@link Executors} class includes a set of methods
   * that can convert some other common closure-like objects,
   * for example, {@link java.security.PrivilegedAction} to
   * {@link Callable} form so they can be submitted.
   *
   * @param task the task to submit
   * @return a Future representing pending completion of the task
   * @throws RejectedExecutionException if the task cannot be
   *     scheduled for execution
   * @throws NullPointerException if the task is null
   */
  <T> Future<T> submit(Callable<T> task);
 
  /**
   * Submits a Runnable task for execution and returns a Future
   * representing that task. The Future's <tt>get</tt> method will
   * return the given result upon successful completion.
   *
   * @param task the task to submit
   * @param result the result to return
   * @return a Future representing pending completion of the task
   * @throws RejectedExecutionException if the task cannot be
   *     scheduled for execution
   * @throws NullPointerException if the task is null
   */
  <T> Future<T> submit(Runnable task, T result);
 
  /**
   * Submits a Runnable task for execution and returns a Future
   * representing that task. The Future's <tt>get</tt> method will
   * return <tt>null</tt> upon <em>successful</em> completion.
   *
   * @param task the task to submit
   * @return a Future representing pending completion of the task
   * @throws RejectedExecutionException if the task cannot be
   *     scheduled for execution
   * @throws NullPointerException if the task is null
   */
  Future<?> submit(Runnable task);

java多线程之Future和FutureTask使用实例

扫一扫手机访问