android Thread和Runable區別,精講(有疑問)

來源:互聯網
上載者:User

標籤:

發現我對Thread和Runable有錯誤的理解,看過源碼後進行區分這兩者。

其一:Runable只是一個介面,不會開啟一個線程,依舊是運行在UI線程中。                     

public interface Runnable {    /**     * Starts executing the active part of the class‘ code. This method is     * called when a thread is started that has been created with a class which     * implements {@code Runnable}.     */    public void run();}

  可以看到,Runable在源碼中只有run方法,並且Runable可以在主線程執行修改UI的代碼,並且“OK”的執行一定是在輸出10個“runable”後,所以,Runable並沒有開啟線程,依舊是運行在UI線程中。

protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        runnable.run();        Log.d("hello", "OK");    }        Runnable runnable = new Runnable() {            @Override            public void run() {                for(int i = 0;i<10;i++) {                    textView.setText("runable");                    Log.d("hello", "runable");                }            }
};

 

其二:Thread如何開啟的線程,和Runable什麼關係?

源碼部分:

public class Thread implements Runnable {

 

最直接的一部分,實現Runable的介面。下面看看Thread的建構函式。

public Thread() {    create(null, null, null, 0);}

 這是其中之一的夠著函數,調用了create()方法,其他建構函式依然調用該方法。下面看看create()方法。

private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {        Thread currentThread = Thread.currentThread();        if (group == null) {            group = currentThread.getThreadGroup();        }        if (group.isDestroyed()) {            throw new IllegalThreadStateException("Group already destroyed");        }        this.group = group;        synchronized (Thread.class) {            id = ++Thread.count;        }        if (threadName == null) {            this.name = "Thread-" + id;        } else {            this.name = threadName;        }            this.target = runnable;
     this.stackSize = stackSize; this.priority = currentThread.getPriority(); this.contextClassLoader = currentThread.contextClassLoader; // Transfer over InheritableThreadLocals. if (currentThread.inheritableValues != null) { inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues); } // add ourselves to our ThreadGroup of choice this.group.addThread(this); }

 

 雖然比較多,但是只需要看這一行代碼,this.taeget = runable;而在Thread類的run()方法和start()方法中,

 

  public void run() {        if (target != null) {            target.run();        }    }

  

/**     * Starts the new Thread of execution. The <code>run()</code> method of     * the receiver will be called by the receiver Thread itself (and not the     * Thread calling <code>start()</code>).     *     * @throws IllegalThreadStateException - if this thread has already started.     * @see Thread#run     */    public synchronized void start() {        checkNotStarted();        hasBeenStarted = true;        nativeCreate(this, stackSize, daemon);    }

 

 

 

這兩個形成了兩個方法的區別:

 

  •   start: 

           用start方法來啟動線程,真正實現了多線程運行,這時無需等待run方法體代碼執行完畢而直接繼續執行下面的代碼。通過調用Thread類的start()方法來啟動一個線程,這時此線程處於就緒(可運行)狀態,並沒有運行,一旦得到cpu時間片,就開始執行run()方法,這裡方法 run()稱為線程體,它包含了要執行的這個線程的內容,Run方法運行結束,此線程隨即終止。

  •   run:
      run()方法只是類的一個普通方法而已,如果直接調用Run方法,程式中依然只有主線程這一個線程,其程式執行路徑還是只有一條,還是要順序執行,還是要等待run方法體執行完畢後才可繼續執行下面的代碼,這樣就沒有達到寫線程的目的。總結:調用start方法方可啟動線程,而run方法只是thread的一個普通方法調用,還是在主線程裡執行。這兩個方法應該都比較熟悉,把需要平行處理的代碼放在run()方法中,start()方法啟動線程將自動調用 run()方法,這是由jvm的記憶體機制規定的。並且run()方法必須是public存取權限,傳回值類型為void.。

 

這樣也就很清晰可見,那麼如何開啟線程,

    其中之一,和上文類比。

 Thread t = new Thread(runnable);        t.start();        Log.d("hello","ok");    }        Runnable runnable = new Runnable() {            @Override            public void run() {
           textview.settext(“runable”);
for(int i = 0;i<10;i++) { Log.d("hello", "runable"); } } };
  1. 執行Thread的構造方法,然後執行oncreate方法。this.target = runable; 
  2. 執行t.start();等得到cpu時間片,執行run()方法。
  3. 執行run()方法,target.run();  (也就是在子線程執行runable.run()。)

根據執行結果也看到真正的開啟了線程,“OK”的輸出並不按代碼執行順序。

 

06-13 19:32:26.252 21369-21369/? D/hello: ok06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable06-13 19:32:26.252 21369-21429/? D/hello: runable

 但是可以修改Ui(textview.settext)?!!!!!!執行的是runable.run()。(不應該在子線程執行這句話嗎?子線程不是不能修改UI嗎?)

   

為其添加按鈕監聽,列印線程 t 的名字,為Thread-76777  

  button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                t.start();            }        });

 得到我想要的結果:: FATAL EXCEPTION: Thread-76777 ,android.view.ViewRootImpl$CalledFromWrongThreadException:

    那麼,問題在於。為什麼上述情況可以修改,而添加按鈕點擊後執行t.start()無法修改UI。

  希望有人看到幫我解答一下這個疑問,如果本文有錯誤也希望指出。

原因:

onCreate中極短的時間內, viewRootImpl還沒有建立完成, new Thread()是可以修改ui的.

因為那個時候viewRootImpl還沒有建立.

當使用按鈕之後, 就不行了. 因為這個時候的view樹肯定是已經建立完畢了. 只有建立該View的線程才能修改和更新改view.
因為ViewRootImpl是在ActivityThread類中的主線程建立的. 所以只有主線程能更新ui.

 

 END!

android Thread和Runable區別,精講(有疑問)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.