多線程是 Java 並發編程的基石。本文從進程/線程概念切入,詳細講解繼承 Thread 與實現 Runnable 兩種創建方式、線程命名技巧、搶佔式調度模型及優先級設置,並附帶完整可運行代碼示例。
java 命令啟動 JVM 進程 → 自動啟動「主線程」調用 main() → 同時存在 GC 線程等守護線程public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 300; i++) System.out.println(i);
}
}
public class Demo {
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public class Demo {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
new Thread(r, "zhangsan").start();
new Thread(r, "lisi").start();
}
}
優勢:避免單繼承限制;同一 Runnable 實例可被多線程共享,實現「代碼與數據分離」,更符合 OO 設計。
| 方法 | 說明 |
|---|---|
setName(String) / getName() | 實例方法,設置/獲取線程名 |
Thread(String name) | 構造方法直接命名 |
Thread.currentThread() | 靜態方法,獲取當前執行代碼所在的線程對象 |
setPriority(int) / getPriority()Thread t1 = new Thread(() -> { /*...*/ }, "High");
Thread t2 = new Thread(() -> { /*...*/ }, "Low");
t1.setPriority(Thread.MAX_PRIORITY); // 10
t2.setPriority(Thread.MIN_PRIORITY); // 1
t1.start(); t2.start();