多線程-Thread與Runnable源碼分析
阿新 • • 發佈:2017-09-23
hat starting cal this oid oev other pri trac
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是個只有一個方法的接口。
Thread:
public class Thread implements Runnable { /* What will be run. */ private Runnable target; /** * If this thread was constructed using a separate * <code>Runnable</code> run object, then that * <code>Runnable</code> object‘s <code>run</code> method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of <code>Thread</code> should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } } }
Thread實現了Runnable接口,而且還組合了一個Runnable,可以看出,實現的方法內部是調用組合類的方法,這其實就是裝飾模式。
多線程-Thread與Runnable源碼分析