java中thread的start()和run()的區別


1.start()方法來啟動線程,真正實現了多線程運行,這時無需等待run方法體代碼執行完畢而直接繼續執行下面的代碼:

通過調用Thread類的start()方法來啟動一個線程, 這時此線程是處於就緒狀態, 並沒有運行。 然后通過此Thread類調用方法run()來完成其運行操作的, 這里方法run()稱為線程體, 它包含了要執行的這個線程的內容, Run方法運行結束, 此線程終止, 而CPU再運行其它線程,

 

2.run()方法當作普通方法的方式調用,程序還是要順序執行,還是要等待run方法體執行完畢后才可繼續執行下面的代碼:

而如果直接用Run方法, 這只是調用一個方法而已, 程序中依然只有主線程--這一個線程, 其程序執行路徑還是只有一條, 這樣就沒有達到寫線程的目的。

 

 

---------------------------------------------------------------------------

package waitio;

public class Thread1 extends Thread{
    public static void main(String[] args) {
        Thread1 one = new Thread1();
        one.setName("one : ");
        Thread1 two = new Thread1();
        two.setName("two : ");
//線程1開啟 one.start();
//線程2 開啟 two.start();
/* one.run();
//這是方法調用,而不是開啟一個線程 two.run();
*/ } @Override public void run() { super.run(); for (int i = 0; i < 10; i++) { System.out.println(currentThread().getName()+" -- "+i); } } }

輸出:

one :      --      0
one :      --      1
one :      --      2
one :      --      3
one :      --      4
one :      --      5
one :      --      6
two :      --      0
two :      --      1
two :      --      2
two :      --      3
two :      --      4
two :      --      5
two :      --      6
two :      --      7
two :      --      8
two :      --      9
one :      --      7
one :      --      8
one :      --      9

 

In Example one the threads will run sequentially:

first, thread number one runs, when it exits the thread number two starts.

In Example two both threads start and run simultaneously.

Conclusion: the start() method call run() method asynchronously (does not wait for any result, just fire up an action), while we run run() method synchronously - we wait when it quits and only then we can run the next line of our code.


免責聲明!

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



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