异步编程之 Future和FutureTask

365 阅读2分钟

Future

Future接口的几个方法

  • boolean cancel(boolean mayInterruptIfRunning); 取消未完成的任务,中断执行中的任务
  • boolean isCancelled(); 是否完成前被取消
  • boolean isDone();
  • V get() throws InterruptedException, ExecutionException; 阻塞当前线程等任务完成
  • V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; 指定一个等待的超时时间
    /**
     * 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 {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code 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 {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns {@code 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
     * {@code true}.
     *
     * @return {@code 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;
}

FutureTask

FutureTask 实现了 Runnable 和 Future 接口,由于实现了 Runnable 接口,所以可以将 FutureTask 对象作为任务提交给ThreadPoolExecutor 去执行,也可以直接被 Thread 执行;又因为实现了 Future 接口,所以也能用来获得任务的执行结果。

茶壶烧水问题

多种办法,例如 Thread.join()、CountDownLatch,甚至阻塞队列都可以解决,不过今天我们用 Future特性来实现。

public class ThreadPoolDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 5, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(), r -> new Thread(r, "bb-thread-" + r.hashCode()));

        FutureTask<String> t1 = new FutureTask<>(new Task1());
        FutureTask<String> t2 = new FutureTask<>(new Task2(t1));
        threadPoolExecutor.submit(t1);
        threadPoolExecutor.submit(t2);
        System.out.println(t2.get());
    }
}


class Task1 implements Callable<String>{

    @Override
    public String call() throws Exception {
        System.out.println("洗茶壶...");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("洗茶杯...");
        TimeUnit.SECONDS.sleep(2);
        System.out.println("拿茶叶...");
        TimeUnit.SECONDS.sleep(1);
        return " 龙井 ";
    }
}

class Task2 implements Callable<String>{
    FutureTask<String> task1futureTask;

    public Task2(FutureTask<String> task1futureTask) {
        this.task1futureTask = task1futureTask;
    }

    @Override
    public String call() throws Exception {
        System.out.println("洗水壶...");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("烧开水...");
        TimeUnit.SECONDS.sleep(5);
        // 获取另外线程的执行结果
        String tf = task1futureTask.get();
        System.out.println("拿到茶叶:"+tf);
        System.out.println("泡茶...");
        return "上茶:" + tf;
    }
}