多執行緒:繼承方式和實現方式的聯絡與區別

小白衝發表於2021-04-11

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

繼承方式和實現方式的聯絡與區別
public class Thread extends Object implements Runnable


區別
 繼承Thread:執行緒程式碼存放Thread子類run方法中。
 實現Runnable:執行緒程式碼存在介面的子類的run方法。


 實現方式的好處
 避免了單繼承的侷限性
 多個執行緒可以共享同一個介面實現類的物件,非常適合多個相同線
程來處理同一份資源。

 

 

/**
* 建立多執行緒的方式二:實現Runnable介面
* 1. 建立一個實現了Runnable介面的類
* 2. 實現類去實現Runnable中的抽象方法:run()
* 3. 建立實現類的物件
* 4. 將此物件作為引數傳遞到Thread類的構造器中,建立Thread類的物件
* 5. 通過Thread類的物件呼叫start()
*
*
* 比較建立執行緒的兩種方式。
* 開發中:優先選擇:實現Runnable介面的方式
* 原因:1. 實現的方式沒有類的單繼承性的侷限性
* 2. 實現的方式更適合來處理多個執行緒有共享資料的情況。
*
* 聯絡:public class Thread implements Runnable
* 相同點:兩種方式都需要重寫run(),將執行緒要執行的邏輯宣告在run()中。
*
* @author ch
* @create 2019-02-13 下午 4:34
*/

 

 

Runnable原始碼展示:
/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@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();
}

 

相關文章