1.start()方法來啟動線程,真正實現了多線程運行,這時無需等待run方法體代碼執行完畢而直接繼續執行下面的代碼:
通過調用Thread類的start()方法來啟動一個線程,
這時此線程是處於就緒狀態,
並沒有運行。
然後通過此Thread類調用方法run()來完成其運行操作的,
這裡方法run()稱為線程體,
它包含了要執行的這個線程的內容,
Run方法運行結束,
此線程終止,
而CPU再運行其它線程,
2.run()方法當作普通方法的方式調用,程式還是要順序執行,還是要等待run方法體執行完畢後才可繼續執行下面的代碼:
而如果直接用Run方法,
這隻是調用一個方法而已,
程式中依然只有主線程--這一個線程,
其程式執行路徑還是只有一條,
這樣就沒有達到寫線程的目的。
通過implements Runnable介面來實現多線程
範例程式碼:
| 代碼如下 |
複製代碼 |
package com; public class TestRunnable implements Runnable{ private int num = 0; public static void main(String[] args) { for(int i=0; i<5; i++){ new Thread(new TestRunnable(i)).start(); } } public TestRunnable(int num) { this.num = num; } //實現方法 public void run(){ System.out.println("線程:"+this.num); } } |
上例列印出來的結果是無序的:
1 4 3 2 0
也可能是別的順序,通過Thread類調用start,真正實現了多線程,不用等待run方法執行完畢再起新線程。
如果將
| 代碼如下 |
複製代碼 |
new Thread(new TestRunnable(i)).start() 改成 new Thread(new TestRunnable(i)).run(), |
則列印出來的結果是由順序的,也就是:
0 1 2 3 4
通過Thread類直接調用run方法,實際上就是調用TestRunnable類的run方法,查看Thread類的run方法:
| 代碼如下 |
複製代碼 |
public void run() { if (target != null) { target.run(); } }
|
發現Thread類run方法就是調用了TestRunnable的run(),所以通過
| 代碼如下 |
複製代碼 |
new Thread(new TestRunnable(i)).run() |
並不是多線程,其執行線程還是主線程。
下面再將Thread類的start方法貼出來,可與上面Thread類的run方法做個對比:
| 代碼如下 |
複製代碼 |
/** * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. * <p> * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * <p> * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } |