public class Calculator implements Runnable {
private final int number;
public Calculator(int number) { this.number = number; }
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.printf("%s: %d * %d = %d%n",
Thread.currentThread().getName(), number, i, i * number);
}
}
}
// 啟動
for (int i = 0; i < 10; i++) {
new Thread(new Calculator(i), "Thread-" + i).start();
}
優勢:職責分離(任務邏輯 與 線程控制解耦)、支持匿名內部類/Lambda、便於提交給線程池(ExecutorService.execute(runnable))。
public class MyThread extends Thread {
@Override public void run() { /* 任務邏輯 */ }
}
// 啟動:new MyThread().start();
劣勢:繼承佔用了唯一的 extends 名額、任務與線程控制耦合、無法直接投入線程池。
⚡ 核心鐵律:必須調用
start()才會創建新線程;直接調用run()只是在當前線程同步執行普通方法,不會開啟新線程。
NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED
new Thread() 但未 start();synchronized);Object.wait()、Thread.join()、LockSupport.park());Thread.sleep()、wait(timeout)、join(timeout));run() 正常返回或拋出未捕獲異常結束。public class ConcurrencyDemo1 {
public static void main(String[] args) {
// Lambda 寫法更簡潔
for (int i = 0; i < 5; i++) {
final int num = i;
new Thread(() -> {
for (int j = 0; j < 5; j++) {
System.out.printf("[%s] %d * %d = %d%n",
Thread.currentThread().getName(), num, j, num * j);
}
}, "Worker-" + i).start();
}
System.out.println("主線程結束,但子線程仍在運行...");
}
}
Runnable(或 Callable),不要繼承 Thread;start();ThreadPoolExecutor 或 Spring @Async 管理;