一、start()方法
1、start()方法含義
1、啓動新線程。當我們執行了start()方法之後這個線程不一定會立刻執行,其實是在告訴jvm中的線程調度器在合適的時間去啓動。例如:我們可能會創建兩個線程,分別是線程1和線程2,但線程1先調用start()方法,線程2後調用,缺發現線程2先執行,這其實是不違背啓動順序的。也就是說調用start()方法的順序並不能決定執行的順序。
2、一個start()方法牽扯到兩個線程:新的線程和原來的主線程。
2、 不能重複的執行start()方法
package threadcoreknowledge.startthread;
/**
* 描述: 演示不能兩次調用start方法,否則會報錯
*/
public class CantStartTwice {
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
thread.start();
}
}
非法的線程狀態
3、start()源碼解析
啓動新線程檢查線程狀態
加入線程組 , 調用start0()
二、run()方法原理解讀
源碼在Thread.java中的746行左右。
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
可以看到run()方法就是一個普普通通的方法,和我們自己寫的普通方法沒有區別,所以要想啓動線程,不能調用run()方法,來間接的調用run()方法。
常見面試題
答:會拋出異常,在start()方法最開始的時候就會對當前狀態進行檢查,如果不符合規定,也就是說已經執行了start()方法,就會拋出異常。
答:調用start()方法纔是真正意義上的啓動線程,它會去經歷線程的各個生命週期。而如果調用run方法,它就是一個普通方法,也不會去用子線程去調用。