原課程B站地址:全面深入學習java併發編程,中級程序員進階必會
衆所周知,線程運行體運行的代碼是重寫Thread類的run()方法,而啓動線程是使用start()方法,那爲什麼直接調用run()方法不行呢?
當調用start()方法啓動線程的時候
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread("t1"){
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("2 running");
}
};
t1.start();
log.debug("1 running");
}
日誌如下
可以看到,線程被正確啓動,主線程main打印1 running,隔了2秒後t1線程打印 2 running。
當調用run()方法啓動線程的時候
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread("t1"){
@Override
public void run() {
//改變一下位置,效果更明顯一些
log.debug("2 running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.run();
log.debug("1 running");
}
日誌如下
可以看到,代碼的執行全是由main線程來操作的,而且代碼是串行執行,1 running等待 2 running執行完兩秒纔開始執行。由此可知,線程t1並沒有被成功創建,這樣做只是簡簡單單調用了一個方法。
結論
直接調用run()方法,會使得代碼在主線程中執行,並沒有開闢一個線程,只有調用start()方法,才能成功開闢一個新的線程。