| 方法 | 作用 | 是否啟動新線程 | 可重複調用 |
|---|---|---|---|
start() | 啟動新線程,由 JVM 調度執行 run() | 是 | 否(重複調用拋 IllegalThreadStateException) |
run() | 普通實例方法,在當前線程同步執行 | 否 | 是 |
class MyThread extends Thread {
@Override public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
public class Demo {
public static void main(String[] args) {
Thread t = new MyThread();
System.out.println(Thread.currentThread().getName() + " call run()");
t.run(); // 輸出: main is running
System.out.println(Thread.currentThread().getName() + " call start()");
t.start(); // 輸出: Thread-0 is running
}
}
main call run()
main is running
main call start()
Thread-0 is running
證明:run() 在主線程執行;start() 建立新線程 Thread-0 執行。
public synchronized void start() {
if (threadStatus != 0) throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0(); // 本地方法,實際創建 OS 線程
started = true;
} finally { ... }
}
private native void start0(); // JVM 內部實現
public void run() {
if (target != null) target.run(); // 若以 Runnable 建構,委派執行
}
thread.run() 以為啟動了線程,實則同步阻塞主線程。thread.start() 啟動線程。Runnable 並多次 new Thread(runnable).start(),或使用執行緒池。start() = 啟動新線程(非同步);run() = 邏輯執行入口(同步)。切勿混淆。