java 線程中start方法與run方法的區(qū)別詳細介紹
線程中start方法與run方法的區(qū)別
在線程中,如果start方法依次調用run方法,為什么我們會選擇去調用start方法?或者在java線程中調用start方法與run方法的區(qū)別在哪里? 這兩個問題是兩個非常流行的初學者級別的多線程面試問題。當一個Java程序員開始學習線程的時候,他們首先會學著去繼承Thread類,重載run方法或者實現(xiàn)Runnable接口,實現(xiàn)run方法,然后調用Thread實例的start方法。但是當他擁有一些經驗之后,他通過查看API文檔或者其他途徑會發(fā)現(xiàn)start方法內部會調用run方法,但是我們中的很多人知道面試時被問到的時候才會意識到這個問題的重要性。在這個java教程里,我們將會明白java中開啟線程的時候調用start方法和run方法的不同的地方
這篇文章是我們再起在Java多線程上發(fā)表的一些文章的后序部分,E.G. Difference between Runnable and Thread in Java AND How to solve Producer Consumer problem in Java using BlockingQueue.如果你還沒有讀過他們,你可能將會發(fā)現(xiàn)他們還是很有趣并且很有用的
在java線程中 start與run的不同
start與run方法的主要區(qū)別在于當程序調用start方法一個新線程將會被創(chuàng)建,并且在run方法中的代碼將會在新線程上運行,然而在你直接調用run方法的時候,程序并不會創(chuàng)建新線程,run方法內部的代碼將在當前線程上運行。大多數情況下調用run方法是一個bug或者變成失誤。因為調用者的初衷是調用start方法去開啟一個新的線程,這個錯誤可以被很多靜態(tài)代碼覆蓋工具檢測出來,比如與fingbugs. 如果你想要運行需要消耗大量時間的任務,你最好使用start方法,否則在你調用run方法的時候,你的主線程將會被卡住。另外一個區(qū)別在于,一但一個線程被啟動,你不能重復調用該thread對象的start方法,調用已經啟動線程的start方法將會報IllegalStateException異常, 而你卻可以重復調用run方法
下面是start方法和run方法的demo
線程中的任務是打印線程傳入的String值 已經當前線程的名字
這里可以明確的看到兩者的區(qū)別
public class DiffBewteenStartAndRun { public static void main(String args[]) { System.out.println(Thread.currentThread().getName()); // creating two threads for start and run method call Thread startThread = new Thread(new Task("start")); Thread runThread = new Thread(new Task("run")); startThread.start(); // calling start method of Thread - will execute in // new Thread runThread.run(); // calling run method of Thread - will execute in // current Thread } /* * Simple Runnable implementation */ private static class Task implements Runnable { private String caller; public Task(String caller) { this.caller = caller; } @Override public void run() { System.out.println("Caller: " + caller + " and code on this Thread is executed by : " + Thread.currentThread().getName()); } } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
使用RocketMQTemplate發(fā)送帶tags的消息
這篇文章主要介紹了使用RocketMQTemplate發(fā)送帶tags的消息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07