@FunctionalInterface 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(); }
@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; }
RunnableFuture作为 Runnable 的 Future。成功执行 run 方法可以完成 Future 并允许访问其结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * 作为 Runnable 的 Future。成功执行 run 方法可以完成 Future 并允许访问其结果。 * A {@link Future} that is {@link Runnable}. Successful execution of * the {@code run} method causes completion of the {@code 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 {@code 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(); }
FutureTask
我们先来看一下FutureTask的实现:
1
public class FutureTask<V> implements RunnableFuture<V>
2018-11-1423:14:23.641 [main] INFO c.f.l.r.CyclicBarrierTest - main going to await 2018-11-1423:14:23.641 [t2] INFO com.fly.learn.reentrantlock.MyThread - t2 going to await 2018-11-1423:14:23.640 [t1] INFO com.fly.learn.reentrantlock.MyThread - t1 going to await 2018-11-1423:14:23.648 [t1] INFO c.f.l.r.CyclicBarrierTest - t1 barrier action 2018-11-1423:14:23.648 [t1] INFO com.fly.learn.reentrantlock.MyThread - t1 continue 2018-11-1423:14:23.649 [t2] INFO com.fly.learn.reentrantlock.MyThread - t2 continue 2018-11-1423:14:23.650 [main] INFO c.f.l.r.CyclicBarrierTest - main continue