国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java 線程中start方法與run方法的區別詳細介紹

2019-11-26 13:30:48
字體:
來源:轉載
供稿:網友

線程中start方法與run方法的區別

在線程中,如果start方法依次調用run方法,為什么我們會選擇去調用start方法?或者在java線程中調用start方法與run方法的區別在哪里?  這兩個問題是兩個非常流行的初學者級別的多線程面試問題。當一個Java程序員開始學習線程的時候,他們首先會學著去繼承Thread類,重載run方法或者實現Runnable接口,實現run方法,然后調用Thread實例的start方法。但是當他擁有一些經驗之后,他通過查看API文檔或者其他途徑會發現start方法內部會調用run方法,但是我們中的很多人知道面試時被問到的時候才會意識到這個問題的重要性。在這個java教程里,我們將會明白java中開啟線程的時候調用start方法和run方法的不同的地方

這篇文章是我們再起在Java多線程上發表的一些文章的后序部分,E.G. 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());       }   } } 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 清苑县| 富宁县| 建阳市| 富源县| 和政县| 仁化县| 遂溪县| 莲花县| 晋城| 花莲县| 吉林市| 桐梓县| 肃南| 西乌珠穆沁旗| 务川| 宣武区| 庆元县| 阜南县| 珲春市| 潜山县| 抚松县| 大新县| 鹰潭市| 玛纳斯县| 凭祥市| 仁化县| 博湖县| 蓬溪县| 东乡族自治县| 越西县| 金华市| 无棣县| 托里县| 宁南县| 荥阳市| 丹棱县| 二手房| 平原县| 会东县| 遵义市| 蓬安县|