Thread的start()方法
public synchronized void start() {
// 如果線程不是"就緒狀態",則拋出異常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 將線程添加到ThreadGroup中
group.add(this);
boolean started = false;
try {
// 通過start0()啟動線程
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
說明:
start()實際上是通過本地方法start0()啟動線程的。而start0()會新運行一個線程,新線程會調用run()方法。
Thread的run()方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
說明:
target是一個Runnable對象。run()就是直接調用Thread線程的Runnable成員的run()方法,并不會新建一個線程。
示例
public class MyThread extends Thread{
public MyThread(String name){
super(name);
}
public void run() {
System.out.println(Thread.currentThread().getName() + " is running.");
}
public static void main(String[] args) {
MyThread myThread = new MyThread("myThread");
System.out.println(Thread.currentThread().getName() + " call myThread.run()");
//在當前線程中運行myThread的run()方法
myThread.run();
System.out.println(Thread.currentThread().getName() + " call myThread.start()");
//啟動一個新線程,并在新線程中運行run()方法
myThread.start();
}
}
運行結果
main call myThread.run() //主線程調用run()方法
main is running. //執行run()方法,不會創建新的線程
main call myThread.start() //主線程通過start()方法啟動新的線程
myThread is running. // 新線程的start方法會調用run()方法