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

Java 多執行緒入門實戰:Thread 繼承與 Runnable 實作完整範例

     編輯:Java 程式設計入門

兩種建立執行緒的方式

  1. 繼承 Thread 類別: 覆寫 run() 方法
  2. 實作 Runnable 介面: 實作 run(),再傳入 Thread 建構子

完整可執行範例程式碼

import java.io.*;

public class MultiThread {
    public static void main(String args[]) {
        System.out.println("我是主執行緒!");

        // 方式1:繼承 Thread
        ThreadUseExtends thread1 = new ThreadUseExtends();

        // 方式2:實作 Runnable
        Thread thread2 = new Thread(new ThreadUseRunnable(), "SecondThread");

        thread1.start();  // 啟動進入就緒狀態
        // thread1.setPriority(6); // 優先級 1-10,預設 5

        System.out.println("主執行緒將掛起 7 秒!");
        try { Thread.sleep(7000); } catch (InterruptedException e) { return; }
        System.out.println("又回到了主執行緒!");

        if (thread1.isAlive()) {
            thread1.stop();  // 注意:stop() 已棄用,教學示範用
            System.out.println("thread1 休眠過長, 主執行緒殺掉了 thread1!");
        } else {
            System.out.println("主執行緒沒發現 thread1, 已順序結束!");
        }

        thread2.start();
        System.out.println("主執行緒又將掛起 7 秒!");
        try { Thread.sleep(7000); } catch (InterruptedException e) { return; }
        System.out.println("又回到了主執行緒!");

        if (thread2.isAlive()) {
            thread2.stop();
            System.out.println("thread2 休眠過長,主執行緒殺掉了 thread2!");
        } else {
            System.out.println("主執行緒沒發現 thread2, 已順序結束!");
        }

        System.out.println("程式結束,按任意鍵繼續!");
        try { System.in.read(); } catch (IOException e) { System.out.println(e); }
    }
}

// 繼承 Thread 類別
class ThreadUseExtends extends Thread {
    public ThreadUseExtends() {}
    public void run() {
        System.out.println("我是 Thread 子類的執行緒實例!");
        System.out.println("我將掛起 10 秒!");
        System.out.println("回到主執行緒, 請稍等...");
        try { sleep(10000); } catch (InterruptedException e) { return; }
        // run() 結束,執行緒自動終止
    }
}

// 實作 Runnable 介面
class ThreadUseRunnable implements Runnable {
    public ThreadUseRunnable() {}
    public void run() {
        System.out.println("我是 Thread 類的執行緒實例並以實作 Runnable 介面的類為參數!");
        System.out.println("我將掛起 1 秒!");
        System.out.println("回到主執行緒, 請稍等...");
        try { Thread.sleep(1000); } catch (InterruptedException e) { return; }
    }
}

關鍵概念解析

概念說明
start() vs run()start() 啟動新執行緒(呼叫 run());直接呼叫 run() 只是普通方法呼叫,不會新開執行緒
執行緒狀態新建 → 就緒 → 執行 → 阻塞/等待 → 終止
優先級1(MIN) ~ 10(MAX),預設 5(NORM);新執行緒繼承父執行緒優先級
sleep()靜態方法,讓當前執行緒暫停指定毫秒,不釋放鎖
stop() 棄用強制終止會導致鎖未釋放、資料不一致;正確做法:interrupt() + 旗標檢查
isAlive()執行緒已啟動且未終止返回 true

現代最佳實踐(替代方案)

  • 優先使用 ExecutorService + Runnable/Callable 管理執行緒池
  • 優雅關閉:executor.shutdown() + awaitTermination()
  • 中斷協作式取消:Thread.currentThread().isInterrupted() 檢查
  • 避免直接操作 Thread 實例,改用高階併發工具(Future、CompletableFuture、CountDownLatch 等)

練習建議

修改程式碼觀察行為差異:調整 sleep() 時間、設定 setPriority()、交換啟動順序、加入 join() 等待終止。

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