| 方法 | 作用 | 能否重複調用 | 是否啟動新線程 |
|---|---|---|---|
start() | 啟動新線程,新線程執行 run() | 否(拋出 IllegalThreadStateException) | 是 |
run() | 普通成員方法,直接在當前線程執行 | 是 | 否 |
// Demo.java
class MyThread extends Thread {
public MyThread(String name) { super(name); }
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
public class Demo {
public static void main(String[] args) {
Thread mythread = new MyThread("mythread");
System.out.println(Thread.currentThread().getName() + " call mythread.run()");
mythread.run(); // 在 main 線程中直接執行
System.out.println(Thread.currentThread().getName() + " call mythread.start()");
mythread.start(); // 啟動新線程執行
}
}
main call mythread.run() main is running <-- run() 在 main 線程執行 main call mythread.start() mythread is running <-- run() 在新線程 mythread 執行
public synchronized void start() {
if (threadStatus != 0) throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0(); // 本地方法,真正啟動新線程
started = true;
} finally { ... }
}
private native void start0();
start0() 是 native 方法,會創建新線程並調用 run()。
public void run() {
if (target != null) {
target.run(); // 直接調用 Runnable 的 run()
}
}
target 是 Runnable 對象。run() 只是普通方法調用,不會創建新線程。