首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 多執行緒實現:Runnable vs Thread 深度對比與資源共享實戰

     編輯:Java 相關知識

兩種實現方式

  1. 繼承 Thread 類別:覆寫 run()。限制:單一繼承,無法繼承其他業務類別。
  2. 實作 Runnable 介面:實作 run(),再透過 new Thread(runnable).start() 啟動。優勢:避開單一繼承限制,天然支援資源共享。

Thread 啟動機制

start() 是 native 方法(JNI),會請求作業系統建立新執行緒並排程執行 run()。直接呼叫 run() 只是普通方法調用,不會開啟新執行緒。

資源共享實戰:售票系統

Thread 版(各賣各的,共賣 30 張)


class MyThread extends Thread {
    private int ticket = 10;
    public void run() {
        for (int i = 0; i < 20; i++)
            if (ticket > 0) System.out.println("賣票:" + ticket--);
    }
}
public class ThreadTicket {
    public static void main(String[] args) {
        new MyThread().start();
        new MyThread().start();
        new MyThread().start(); // 三個實例,各有 10 張票
    }
}

Runnable 版(共享 10 張票)


class MyThread implements Runnable {
    private int ticket = 10;
    public void run() {
        for (int i = 0; i < 20; i++)
            if (ticket > 0) System.out.println("賣票:" + ticket--);
    }
}
public class RunnableTicket {
    public static void main(String[] args) {
        MyThread mt = new MyThread(); // 單一實例
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start(); // 三執行緒共享同一 ticket
    }
}

核心差異總結

維度繼承 Thread實作 Runnable
繼承限制單一繼承,無法擴展其他類可同時實作多介面、繼承業務類
資源共享需額外機制(static/外部物件)天然共享同一 Runnable 實例的欄位
耦合度執行緒邏輯與任務邏輯耦合任務邏輯獨立,交由 Thread 執行
Thread 關係本身即 Thread 子類Thread 接受 Runnable 為目標

原始碼佐證

public class Thread extends Object implements Runnable { ... }

Thread 本身實作了 Runnable,Thread(Runnable target) 建構子將任務委派給目標物件。

最佳實踐建議

  1. 業務開發優先使用 Runnable(或 Java 8+ Lambda),靈活解耦。
  2. 需自訂執行緒行為(如覆寫 interrupt()、設定優先權)時再考慮繼承 Thread。
  3. 配合執行緒池(ExecutorService)提交 Runnable/Callable,進一步分離任務提交與執行緒管理。

總結

理解 Runnable 與 Thread 的關係與差異,掌握資源共享的實現方式,是編寫高併發、可維護 Java 多執行緒程式的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved