Java線程啟動為什么要用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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatis中select語句中使用String[]數(shù)組作為參數(shù)的操作方法
在 MyBatis 中,如何在 mapper.xml 配置文件中 select 語句中使用 String[] 數(shù)組作為參數(shù)呢,并且使用IN關鍵字來匹配數(shù)據(jù)庫中的記錄,這篇文章主要介紹了MyBatis中select語句中使用String[]數(shù)組作為參數(shù),需要的朋友可以參考下2023-12-12使用sharding-jdbc實現(xiàn)水平分庫+水平分表的示例代碼
本文主要介紹了使用sharding-jdbc實現(xiàn)水平分庫+水平分表,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12Java報錯:Error:java:?程序包org.springframework.boot不存在解決辦法
建完springboot項目時,點擊啟動,有可能會報錯,下面這篇文章主要給大家介紹了關于Java報錯:Error:java:?程序包org.springframework.boot不存在的解決辦法,需要的朋友可以參考下2024-02-02Kafka 網(wǎng)絡中斷和網(wǎng)絡分區(qū)4種場景分析
這篇文章主要介紹了Kafka 網(wǎng)絡中斷和網(wǎng)絡分區(qū)4種場景分析2007-02-02Mybatis使用XML實現(xiàn)動態(tài)sql的示例代碼
當編寫 MyBatis 中復雜動態(tài) SQL 語句時,使用 XML 格式是一種非常靈活的方式,本文主要為大家詳細介紹了Mybatis使用XML實現(xiàn)動態(tài)sql的具體方法,需要的可以參考下2023-12-12Springboot整合SpringSecurity的完整案例詳解
Spring Security是基于Spring生態(tài)圈的,用于提供安全訪問控制解決方案的框架,Spring Security登錄認證主要涉及兩個重要的接口 UserDetailService和UserDetails接口,本文對Springboot整合SpringSecurity過程給大家介紹的非常詳細,需要的朋友參考下吧2024-01-01