java基础:Future简介

458 阅读2分钟

一、Runnable和Callable

经常会将一个任务放在一个子线程或者线程池中执行。主线程怎么获取在子线程执行的任务结果呢?如果任务在子线程中抛出了异常,主线程可以感知吗?

1. Runnable

看下Runnable的java定义:

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

可以看到run()方法既不会返回结果,也不会抛出异常。

2. Callable

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
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;
}

从上面的注释可以发现:Runnable既不会有返回值,也不能抛出checked exception。虽然checked exception可以通过在方法名中throws出来,但是Runnable的run方法却不行,只能通过try catch的方式。但是Callable既可以返回结果,又可以抛出异常。

3. 示例

public class FutureTest {

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Test
    public void testRunnableException() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("running...");
                throw new RuntimeException("runnable throw exception");
            }
        });

        sleep(500);
        System.out.println("main over");
    }

    private void sleep(long timeMs) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeMs);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testCallableException() {
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                if (Math.random() < 0.5) {
                    throw new RuntimeException("callable throw exception");
                }
                return "callable";
            }
        });

        try {
            String res = future.get();
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        sleep(500);
        System.out.println("main over");
    }
}

运行结果:

// testRunnableException
running...
// 可以看到这个异常在线程“pool-1-thread-1”中
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: runnable throw exception
  at FutureTest$1.run(FutureTest.java:16)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
  at java.base/java.lang.Thread.run(Thread.java:834)
main over


// testCallableException
// 可以看到在main线程中捕获了ExecutionException,caused by是RuntimeException
java.util.concurrent.ExecutionException: java.lang.RuntimeException: callable throw exception
  at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
  at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
  at FutureTest.testCallableException(FutureTest.java:45)
Caused by: java.lang.RuntimeException: callable throw exception
  at FutureTest$2.call(FutureTest.java:38)
  at FutureTest$2.call(FutureTest.java:34)
  at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
  at java.base/java.lang.Thread.run(Thread.java:834)
main over


// testCallableException
callable
main over

二、Future

那么Future有什么魔力可以在一个线程中获得另一个线程的执行结果?又怎么在一个线程中捕获了另一个线程的异常(虽然封装了一层ExecutionException)?先来看看Future的java定义。

1. Future定义

/**
 * A {@code 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
 * {@code get} when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * {@code 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 {@code Future} for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return {@code null} as a result of the underlying task.
 *
 * <p><b>Sample Usage</b> (Note that the following classes are all
 * made-up.)
 *
 * <pre> {@code
 * interface ArchiveSearcher { String search(String target); }
 * class App {
 *   ExecutorService executor = ...
 *   ArchiveSearcher searcher = ...
 *   void showSearch(String target) throws InterruptedException {
 *     Callable<String> task = () -> searcher.search(target);
 *     Future<String> future = executor.submit(task);
 *     displayOtherThings(); // do other things while searching
 *     try {
 *       displayText(future.get()); // use future
 *     } catch (ExecutionException ex) { cleanup(); return; }
 *   }
 * }}</pre>
 *
 * The {@link FutureTask} class is an implementation of {@code Future} that
 * implements {@code Runnable}, and so may be executed by an {@code Executor}.
 * For example, the above construction with {@code submit} could be replaced by:
 * <pre> {@code
 * FutureTask<String> future = new FutureTask<>(task);
 * 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 {@code 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 {@code get} method
 */
public interface Future<V>

正如注释所说:Future表示异步执行的结果。Future提供的这些方法用于检测任务是否完成、等待任务完成、获取计算结果。通过get方法可以获得结果,但是有可能会等待任务计算完成。cancel方法可以取消任务(但是任务一旦完成,就不能被取消了)。如果不想要返回值,但是却想cancel任务,可以通过Future<?>并返回null的方式实现。

FutureTask是Future的一个实现。

注释写的太清楚了,直接搬运过来了。


    /**
     * 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);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @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;

测试代码:

@Test
public void testCallableCancel() {
    Future<?> future = executorService.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            System.out.println("callable running");
            sleep(1000);
            return null;
        }
    });

    // 注释这句sleep有不同的输出
    sleep(5);

    System.out.println("task state, isDone: " + future.isDone() + "; isCancelled: " + future.isCancelled());

    boolean canceled = future.cancel(true);
    System.out.println("future cancel result: " + canceled);
    System.out.println("task state, isDone: " + future.isDone() + "; isCancelled: " + future.isCancelled());


    canceled = future.cancel(true);
    System.out.println("again, future cancel result: " + canceled);
    System.out.println("task state, isDone: " + future.isDone() + "; isCancelled: " + future.isCancelled());
}

执行结果:

// 有sleep(5);
callable running
task state, isDone: false; isCancelled: false
future cancel result: true
// 已经取消的任务,isDone返回的也是true
task state, isDone: true; isCancelled: true
// 已经取消的任务,再次取消是失败的,返回false
again, future cancel result: false
task state, isDone: true; isCancelled: true
java.lang.InterruptedException: sleep interrupted
  at java.base/java.lang.Thread.sleep(Native Method)
  at java.base/java.lang.Thread.sleep(Thread.java:339)
  at java.base/java.util.concurrent.TimeUnit.sleep(TimeUnit.java:446)
  at FutureTest.sleep(FutureTest.java:26)
  at FutureTest.access$000(FutureTest.java:7)
  at FutureTest$3.call(FutureTest.java:65)
  at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
  at java.base/java.lang.Thread.run(Thread.java:834)


// 没有sleep(5);
// 可以看到task没有执行
task state, isDone: false; isCancelled: false
future cancel result: true
task state, isDone: true; isCancelled: true
again, future cancel result: false
task state, isDone: true; isCancelled: true

这篇文章有点长了,再写一篇文章分析Future的原理:怎么获取的结果,怎么抛出的异常。

硬广告

欢迎关注公众号:double6