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

Java 執行緒實作方式二:實作 Runnable 介面

     編輯:Java 程式設計入門

實作 Runnable 介面:關注點分離

實作 Runnable 介面將「任務邏輯」與「執行緒控制」分離,符合組合優於繼承原則,也是執行緒池、Callable、Future 等進階 API 的基礎模式。

完整程式碼:twothread.java

public class twothread implements Runnable {

    // 建構子:建立並啟動第二條執行緒
    twothread() {
        // 取得主執行緒
        Thread t1 = Thread.currentThread();
        t1.setName("The first main thread");
        System.out.println("The running thread: " + t1);

        // 以「this(Runnable 實例)」+ 名稱建立新執行緒
        Thread t2 = new Thread(this, "the second thread");
        System.out.println("creat another thread");
        t2.start(); // 啟動 t2

        try {
            System.out.println("first thread will sleep");
            Thread.sleep(3000); // 主執行緒休眠 3 秒
        } catch (InterruptedException e) {
            System.out.println("first thread has wrong");
        }
        System.out.println("first thread exit");
    }

    // 實作 Runnable 唯一抽象方法
    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("Sleep time for thread 2: " + i);
                Thread.sleep(1000); // 子執行緒每秒列印一次
            }
        } catch (InterruptedException e) {
            System.out.println("thread has wrong");
        }
        System.out.println("second thread exit");
    }

    public static void main(String args[]) {
        new twothread(); // 建構子內已啟動執行緒
    }
}

執行流程與輸出示意

The running thread: Thread[The first main thread,5,main]
creat another thread
first thread will sleep
Sleep time for thread 2: 0
Sleep time for thread 2: 1
Sleep time for thread 2: 2
Sleep time for thread 2: 3
Sleep time for thread 2: 4
second thread exit
first thread exit

核心概念對照表

概念繼承 Thread實作 Runnable
關係是一個執行緒是一個任務
繼承限制受單繼承限制可自由繼承其他類別
共享資料需額外處理天然適合多執行緒共享同一任務實例
執行緒池相容不直接支援完美支援 ExecutorService
取得執行緒資訊this.getName()Thread.currentThread().getName()

進階應用:多執行緒共享同一 Runnable 實例

public class SharedTask implements Runnable {
    private int counter = 0;

    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " counter=" + counter++);
        }
    }

    public static void main(String[] args) {
        SharedTask task = new SharedTask(); // 單一任務實例
        new Thread(task, "Thread-A").start();
        new Thread(task, "Thread-B").start();
        new Thread(task, "Thread-C").start();
    }
}

輸出會顯示三條執行緒共同操作同一 counter,驗證共享資料特性(亦暴露執行緒安全問題,需同步機制解決)。

最佳實務建議

  1. 優先選擇 Runnable:彈性高、解耦合、相容現代並發 API
  2. 搭配 ExecutorService:executor.submit(new MyTask()) 替代手動 new Thread()
  3. 需回傳值用 Callable:Callable<V> 配合 Future<V> 取得非同步結果
  4. Lambda 簡化語法 (Java 8+):new Thread(() -> { /* 邏輯 */ }).start()

實作 Runnable 是 Java 並發程式設計的基石,掌握其精髓才能駕馭更高階的並發框架。

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