?本文通過一個簡單案例,講解如何通過繼承
Thread
類來實現多線程程序,并詳細分析了代碼結構與運行機制。
一、前言
在 Java 中,實現多線程主要有兩種方式:
-
繼承
Thread
類 -
實現
Runnable
接口
本文以繼承 Thread
類為例,通過一個簡單的例子來帶大家理解線程的基本創建與啟動流程。
二、示例代碼
下面是本次講解的完整代碼:
package thread.test;// 定義一個繼承自 Thread 類的 MyThread2 類
class MyThread2 extends Thread {// 重寫 run() 方法,定義線程執行的任務@Overridepublic void run() {// 無限循環,讓線程持續執行while (true) {// 打印 "hello thread"System.out.println("hello thread");// 讓當前線程休眠 1 秒鐘try {Thread.sleep(1000);} catch (InterruptedException e) {// 處理線程被中斷的異常throw new RuntimeException(e);}}}
}public class ThreadDemo2 {public static void main(String[] args) {// 創建 MyThread2 類的實例Thread myThread2=new MyThread2();// 調用 start() 方法啟動新線程myThread2.start();// 主線程中的無限循環while (true) {// 打印 "hello main"System.out.println("hello main");// 主線程也休眠 1 秒鐘try {Thread.sleep(1000);} catch (InterruptedException e) {// 處理線程被中斷的異常throw new RuntimeException(e);}}}}
三、代碼詳解
1. 定義線程類
通過繼承 Thread
類,并重寫 run()
方法,定義線程要執行的邏輯。
class MyThread2 extends Thread {@Overridepublic void run() {while (true) {System.out.println("hello thread");Thread.sleep(1000);}}
}
-
通過
new
創建線程對象。 -
調用
start()
方法來真正啟動一個新線程。-
start()
方法內部會調用底層操作系統開辟新線程,并最終執行run()
方法。 -
如果直接調用
run()
,則只是普通的方法調用,不會開啟新線程!
-
3. 主線程與子線程并發執行
主線程本身也進入一個無限循環:
while (true) {System.out.println("hello main");Thread.sleep(1000);
}
-
主線程也每秒打印一次
"hello main"
。 -
這樣,主線程和子線程各自獨立運行,同時輸出不同的信息。
四、程序運行結果
運行程序后,控制臺將交替輸出:
hello main
hello thread
hello thread
hello main
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
^C進程已結束,退出代碼為 130 (interrupted by signal 2:SIGINT)
但由于線程調度由操作系統控制,因此有時候輸出順序不一定完全規律,比如連續兩次出現 "hello thread"
或 "hello main"
都是正常的。
五、注意事項
-
線程安全:本例子中各線程互不干擾。但在實際開發中,如果多個線程操作共享資源,需要考慮線程安全問題。
-
優雅地處理中斷:在捕獲
InterruptedException
后,實際項目中建議打斷循環或優雅退出,而不是簡單地拋出異常。 -
線程銷毀:本例代碼是無限循環,因此線程不會主動退出,實際開發中應該根據業務邏輯合理控制線程生命周期。
六、總結
通過繼承 Thread
類,我們可以快速創建并啟動一個新線程,但這種方式有一定局限性,比如:
-
Java 單繼承的局限(一個類只能繼承一個父類)
-
擴展性較差
因此,在實際開發中,更推薦實現 Runnable
接口來創建線程,能夠讓代碼更加靈活、解耦。
不過,對于初學者來說,通過繼承 Thread
來理解線程基本運行原理是非常重要的一步!