Java Thread多線程的start()和run()

來源:互聯網
上載者:User

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 */
            }
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.