start方法和run方法啟動(dòng)線程
public class StartAndRunMethod {
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName());
};
runnable.run();
new Thread(runnable).start();
}
}
start()方法源碼:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
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 */
}
}
}
- 將該線程加入線程組
- 啟動(dòng)新線程
- 處于就緒狀態(tài)讥耗,等待CPU分配資源
- 獲取到CPU分配的資源后,系統(tǒng)會(huì)調(diào)用thread的run()方法執(zhí)行線程
多個(gè)線程顷窒,調(diào)用start()方法的順序,并不是真正執(zhí)行線程的順序。
run()方法
源碼:
@Override
public void run() {
if (target != null) {
target.run();
}
}
啟動(dòng)線程要調(diào)用start()方法豁状,間接的去調(diào)用run()方法