【轉】run方法與start方法的區別


 在java線程中 start與run的不同
start與run方法的主要區別在於當程序調用start方法一個新線程將會被創建,並且在run方法中的代碼將會在新線程上運行,然而在你直接調用run方法的時候,程序並不會創建新線程,run方法內部的代碼將在當前線程上運行。大多數情況下調用run方法是一個bug或者變成失誤。因為調用者的初衷是調用start方法去開啟一個新的線程,這個錯誤可以被很多靜態代碼覆蓋工具檢測出來,比如與fingbugs. 如果你想要運行需要消耗大量時間的任務,你最好使用start方法,否則在你調用run方法的時候,你的主線程將會被卡住。另外一個區別在於,一但一個線程被啟動,你不能重復調用該thread對象的start方法,調用已經啟動線程的start方法將會報IllegalStateException異常,  而你卻可以重復調用run方法

 1     public static void main(String[] args) {  
 2         System.out.println(Thread.currentThread().getName());  
 3         // creating two threads for start and run method call  
 4         Thread startThread = new Thread(new Task("start"));  
 5         Thread runThread = new Thread(new Task("run"));  
 6   
 7   
 8         startThread.start(); // calling start method of Thread - will execute in  
 9                                 // new Thread  
10         runThread.run(); // calling run method of Thread - will execute in  
11                             // current Thread  
12     }  
13     
14     /* 
15      * Simple Runnable implementation 
16      */  
17     private static class Task implements Runnable {  
18         private String caller;  
19   
20   
21         public Task(String caller) {  
22             this.caller = caller;  
23         }  
24   
25   
26         @Override  
27         public void run() {  
28             System.out.println("Caller: " + caller  
29                     + " and code on this Thread is executed by : "  
30                     + Thread.currentThread().getName());  
31   
32   
33         }  
34     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM