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

Java 多線程核心:Runnable vs Thread 區別與選型指南

     編輯:Java 相關知識

兩種實現方式

1. 繼承 Thread 類


class MyThread extends Thread {
    private String name;
    public MyThread(String name) { this.name = name; }
    @Override public void run() {
        for (int i=0; i<10; i++) System.out.println("線程:" + name + ", i=" + i);
    }
}
public static void main(String[] args) {
    new MyThread("A").start();
    new MyThread("B").start();
}

缺點:單繼承限制,數據不共享(每個實例獨立 tickets)。

2. 實現 Runnable 接口(推薦)


class MyRunnable implements Runnable {
    private String name;
    public MyRunnable(String name) { this.name = name; }
    @Override public void run() { /* 同邏輯 */ }
}
public static void main(String[] args) {
    new Thread(new MyRunnable("A")).start();
    new Thread(new MyRunnable("B")).start();
}

深度對比

維度繼承 Thread實現 Runnable
繼承限制單繼承,無法複用其他類邏輯可實現多接口,靈活複用
數據共享每個 Thread 實例獨立數據同一 Runnable 實例可被多線程共享
職責分離任務邏輯與線程控制耦合任務(Runnable)與執行者(Thread)分離
線程池支持不直接支持 ExecutorService原生適配 ExecutorService.submit(Runnable)
底層關係Thread 實現了 RunnableRunnable 是任務抽象,Thread 是執行載體

賣票案例:Runnable 實現共享


class TicketTask implements Runnable {
    private int tickets = 10;
    @Override public void run() {
        for (int i=0; i<20; i++) 
            if (tickets > 0) System.out.println("賣票:" + tickets--);
    }
}
public static void main(String[] args) {
    TicketTask task = new TicketTask(); // 單一實例
    new Thread(task).start();
    new Thread(task).start();
    new Thread(task).start(); // 總共賣 10 張
}

三線程共享同一 tickets 變量,實現真正的資源共享。

結論

實戰開發中 99% 場景應使用 Runnable(或 Callable)+ 線程池。繼承 Thread 僅用於極簡原型或教學演示。

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