Runnable接口源碼
@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(); }
Runnable 接口應該由那些打算通過某一線程執行其實例的類來實現。類必須定義一個稱為 run 的無參數方法。
設計該接口的目的是為希望在活動時執行代碼的對象提供一個公共協議。例如,Thread 類實現了 Runnable。激活的意思是說某個線程已啟動並且尚未停止。
此外,Runnable 為非 Thread 子類的類提供了一種激活方式。通過實例化某個 Thread 實例並將自身作為運行目標,
就可以運行實現 Runnable 的類而無需創建 Thread 的子類。大多數情況下,如果只想重寫 run() 方法,
而不重寫其他 Thread 方法,那么應使用 Runnable 接口。這很重要,因為除非程序員打算修改或增強類的基本行為,否則不應為該類創建子類。
Callable接口源碼
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; }
返回結果並且可能拋出異常的任務。實現者定義了一個不帶任何參數的叫做 call 的方法。 Callable 接口類似於 Runnable,兩者都是為那些其實例可能被另一個線程執行的類設計的。但是 Runnable 不會返回結果,並且無法拋出經過檢查的異常。 Executors 類包含一些從其他普通形式轉換成 Callable 類的實用方法。
區別:
- callable可以拋異常, runnable不能
- callable可以有返回值, runnable不能
相同點:
- 兩者都是接口;
- 兩者都可用來編寫多線程程序;
- 兩者都需要調用Thread.start()啟動線程;