2011-07-25 44 views
0
onCreate(Bundle savedInstanceState){ 
    // show dialog A if something is not correct 
    new Thread(){ 
     public void run(){ 
       if(something is wrong) { 
        runOnUIThread(new Runnable(){ 
         public void run(){ 
          showDialog(A); 
         } 
        }); 
       } 
     } 
    }.start(); 
    // show dialog B 
    showDialog(B); 
} 

我想知道機器人的工作線程和UI線程

  1. 哪個對話框將首先顯示,並且是爲了不確定的?爲什麼?
  2. 如果訂單是不確定的,我如何再現B之前顯示A的情況?

謝謝!

+0

的Util現在,我不知道哪個答案是正確的,任何人請... – tonykwok

回答

1
  1. 哪個對話框將首先顯示沒有定義,你不應該依賴上面發生的對話框之一。線程調度器在所有情況下都不具有相同的確定性。
  2. 您需要鎖定互斥鎖(或任何其他鎖定設備)以確保其中一個顯示在另一個之前。
0

只有知道A是否會顯示,您才能顯示B.所以你不得不等待工作者線程。是否有可能把showDialog(B)放入你的其他線程中?

onCreate(Bundle savedInstanceState){ 
    // show dialog A if something is not correct 
    new Thread(){ 
     public void run(){ 
       runOnUiThread(new Runnable(){ 
        public void run(){ 
         if(something is wrong) { 
          showDialog(A); 
         } 
         showDialog(B); 
        } 
       }); 
       } 
     } 
    }.start(); 
} 
1

關於哪個對話框首先顯示的問題是不確定的。有些情況下,訂單會翻轉。但是通常B會在9/10之後首先顯示,它會在你的線程檢測到有問題之前將它的事件放在UI線程上。

我建議使用AsyncTask來執行啓動所需的任何機制,然後在onPostExecute()允許您的程序恢復啓動,因此它可以顯示Dialog(B),無論它需要什麼。這樣,如果對話框A顯示,您可以停止啓動過程並且不顯示b。

public class MyAsyncStartup extends AsyncTask<Integer,Integer,MyResult> { 
    MyActivity activity; 

    public MyResult handleBackground() { 
     if(somethingWentWrong) return null; 
    } 

    public onPostExecute(MyResult result) { 
      if(result == null) { 
      showDialog(B); 
      } else { 
      activity.resumeStartupAndShowA(); 
      } 
    } 
} 
1
  1. 我不認爲這有可能是A是B之前顯示......這是因爲runOnUIThread添加事件到事件隊列的末尾。該事件中的代碼(顯示對話框A)不會在onCreate()完成之後才執行(這意味着首先顯示對話框B)。

不能保證的是顯示對話框B和調用runOnUIThread之間的順序,但這並不重要。下面是從官方文檔片段:

[runOnUIThread] Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

  1. N/A
+0

是的,這是正確的,因爲onCreate()將繼續運行直到完成,直到導致onCreate被調用的消息完成後才能顯示A. – cyngus