Java線程啟動為什么要用start()而不是run()?
更新時間:2021年12月12日 10:56:54 作者:bkpp976
這篇文章主要介紹了線程啟動為什么要用start()而不是run()?下面文章圍繞start()與run()的相關資料展開詳細內容,具有一定的參考價值,西藥的小火熬版可以參考一下,希望對你有所幫助
1、直接調用線程的run()方法
public class TestStart {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run() {
System.out.println("Thread t1 is working..."+System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.run();
Thread.sleep(2000);
System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
}
}

可以看到主線程在t1.run()運行之后再過三秒才繼續(xù)運行,也就是說,直接在主方法中調用線程的run()方法,并不會開啟一個線程去執(zhí)行run()方法體內的內容,而是同步執(zhí)行。
2、調用線程的start()方法
public class TestStart {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run() {
System.out.println("Thread t1 is working..."+System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
Thread.sleep(2000);
System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
}
}

startVSrun1.JPG 可以看到在,在執(zhí)行完t1.start()這一行之后,主線程立馬繼續(xù)往下執(zhí)行,休眠2s后輸出內容。 也就是說,t1線程和主線程是異步執(zhí)行的,主線程在線程t1的start()方法執(zhí)行完成后繼續(xù)執(zhí)行后面的內容,無需等待run()方法體的內容執(zhí)行完成。
3、總結
- 1、開啟一個線程必須通過
start()方法,直接調用run()方法并不會創(chuàng)建線程,而是同步執(zhí)行run()方法中的內容。 - 2、如果通過傳入一個
Runnable對象創(chuàng)建線程,線程會執(zhí)行Runnable對象的run()方法;否則執(zhí)行自己本身的run()方法。 - 3、不管是實現(xiàn)
Runnable接口還是繼承Thread對象,都可以重寫run()方法,達到執(zhí)行設定的任務的效果。
到此這篇關于線程啟動為什么要用start()而不是run()?的文章就介紹到這了,更多相關start()與run()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

