Thread的run()與start()的區別

Java中thread的start()和run()的區別:

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

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

 

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

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

 

舉例說明一下:

記住:線程就是爲了更好地利用CPU,
提高程序運行速率的!

public class TestThread1{
public static void main(String[] args){
Runner1 r=new Runner1();
//r.run();//這是方法調用,而不是開啓一個線程
Thread t=new Thread(r);//調用了Thread(Runnable target)方法。且父類對象變量指向子類對象。
t.start();

for(int i=0;i<100;i++){
System.out.println("進入Main Thread運行狀態");
System.out.println(i);
}
}
}
class Runner1 implements Runnable{ //實現了這個接口,jdk就知道這個類是一個線程
public void run(){

for(int i=0;i<100;i++){
System.out.println("進入Runner1運行狀態");
System.out.println(i);
}
}
}

同時摘取一段外文網站論壇上的解釋:
Why do we need start() method in Thread class? In Java API description for Thread class is written : "Java Virtual Machine calls the run method of this thread..".

Couldn't we call method run() ourselves, without doing double call: first we call start() method which calls run() method? What is a meaning to do things such complicate?



 

There is some very small but important difference between using start() and run() methods. Look at two examples below:

Example one:

Code:

Thread one = new Thread();
Thread two = new Thread();
one.run();
two.run();

Example two:

Code:

Thread one = new Thread();
Thread two = new Thread();
one.start();
two.start();

The result of running examples will be different.

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.
發佈了43 篇原創文章 · 獲贊 165 · 訪問量 177萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章