線程中start方法與run方法的區別
在線程中,如果start方法依次調用run方法,為什麼我們會選擇去調用start方法?或者在java線程中調用start方法與run方法的區別在哪裡? 這兩個問題是兩個非常流行的初學者級別的多線程面試問題。當一個Java程序員開始學習線程的時候,他們首先會學著去繼承Thread類,重載run方法或者實現Runnable接口,實現run方法,然後調用Thread實例的start方法。但是當他擁有一些經驗之後,他通過查看API文檔或者其他途徑會發現start方法內部會調用run方法,但是我們中的很多人知道面試時被問到的時候才會意識到這個問題的重要性。在這個java教程裡,我們將會明白java中開啟線程的時候調用start方法和run方法的不同的地方
這篇文章是我們再起在Java多線程上發表的一些文章的後序部分,EG Difference between Runnable and Thread in Java AND How to solve Producer Consumer problem in Java using BlockingQueue.如果你還沒有讀過他們,你可能將會發現他們還是很有趣並且很有用的
在java線程中start與run的不同
start與run方法的主要區別在於當程序調用start方法一個新線程將會被創建,並且在run方法中的代碼將會在新線程上運行,然而在你直接調用run方法的時候,程序並不會創建新線程,run方法內部的代碼將在當前線程上運行。大多數情況下調用run方法是一個bug或者變成失誤。因為調用者的初衷是調用start方法去開啟一個新的線程,這個錯誤可以被很多靜態代碼覆蓋工具檢測出來,比如與fingbugs. 如果你想要運行需要消耗大量時間的任務,你最好使用start方法,否則在你調用run方法的時候,你的主線程將會被卡住。另外一個區別在於,一但一個線程被啟動,你不能重複調用該thread對象的start方法,調用已經啟動線程的start方法將會報IllegalStateException異常, 而你卻可以重複調用run方法
下面是start方法和run方法的demo
線程中的任務是打印線程傳入的String值已經當前線程的名字
這裡可以明確的看到兩者的區別
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()); } } }感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!