@FunctionalInterface publicinterfaceRunnable { /** * 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() */ publicabstractvoidrun(); }
@FunctionalInterface publicinterfaceCallable<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
Callable
返回值
无返回值
有返回值(泛型)
异常
用户捕获异常
可以抛出异常
执行
ExecutorService#submit()
ExecutorService#submit() or ExecutorService#execute()
与 Thread 类关系
new Thread(Runnable target).start() 启动(Thread 类就实现了 Runnable 接口)
publicinterfaceRunnableFuture<V> extendsRunnable, Future<V> { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ voidrun(); }
/** * The run state of this task, initially NEW. The run state * transitions to a terminal state only in methods set, * setException, and cancel. During completion, state may take on * transient values of COMPLETING (while outcome is being set) or * INTERRUPTING (only while interrupting the runner to satisfy a * cancel(true)). Transitions from these intermediate to final * states use cheaper ordered/lazy writes because values are unique * and cannot be further modified. * * Possible state transitions: * NEW -> COMPLETING -> NORMAL * NEW -> COMPLETING -> EXCEPTIONAL * NEW -> CANCELLED * NEW -> INTERRUPTING -> INTERRUPTED */ privatevolatileint state; privatestaticfinalintNEW=0; privatestaticfinalintCOMPLETING=1; privatestaticfinalintNORMAL=2; privatestaticfinalintEXCEPTIONAL=3; privatestaticfinalintCANCELLED=4; privatestaticfinalintINTERRUPTING=5; privatestaticfinalintINTERRUPTED=6;
FutureTask 类中重要的就是 state 变量,并且对该变量定义了七种常量类型,一个 FutureTask 任务的执行过程就是在这些状态中流转的过程。最初是在 FutureTask 的构造方法中,会初始化 state 为 NEW 类型,所有流转都以该状态为起始。