2012-04-12 25 views
0
Private static ProgressDialog loading; 

public void downloadData(){ 
    Thread t = new Thread(){ 
     public void run(){ 
      //download stuff 
     } 
     handler.sendEmptyMessage(0); 
    }; 
    t.start(); 
    try{ 
     t.join(); 
    }catch(InterruptedException ignore){} 
} 

private Handler handler = new Handler(){ 
    @Override 
    public void handleMessage(Message msg) { 
     loading.dismiss(); 
    } 
}; 

當我在不使用t.join()的情況下調用donloadData時,它會顯示ProgressDialog。在線程上使用join()時不顯示進度條

但是,當使用t.join()時,t線程似乎正確執行,但ProgressDialog未顯示。爲什麼ProgressDialog不顯示?

有關如何更改的建議,以便我可以使用t.join()並顯示ProgressDialog

+1

你爲什麼這樣做? 't.start()'後跟't.join()'在功能上與't.run()'相同,除了浪費另一個線程堆棧和多個上下文切換。 – EJP 2012-04-12 01:47:44

+0

ProgressDialog未顯示,因爲您正在使用join()。所以,如果你想顯示ProgressDialog,不要使用join()。爲什麼你想在start()之後直接使用join()?你也可以完全忘記這個線程,只需調用下載的東西即可。 – 2012-04-12 01:50:11

+0

線程的要點是你的程序可以同時做兩件事。如果第一個線程只是坐着等待第二個線程,那麼創建第二個線程沒有意義;只是做第一個工作。 – Wyzard 2012-04-12 01:50:47

回答

0

t.join方法會阻止當前線程使用t thread完成它的工作。

試試這個:

Private static ProgressDialog loading; 

public void downloadData(){ 
    Thread t = new Thread(){ 
     public void run(){ 
      //download stuff 

     //edit: when finish down load and send dismiss message 
     handler.sendEmptyMessage(0); 
     } 
     //handler.sendEmptyMessage(0); 
    }; 

    //edit: before start make the dialog show 
    loading.show(); 

    t.start(); 
    //edit: the join method is not necessary 
    try{ 
     t.join(); 
    }catch(InterruptedException ignore){} 
} 

private Handler handler = new Handler(){ 
    @Override 
    public void handleMessage(Message msg) { 
     loading.dismiss(); 
    } 
}; 

上面的代碼可能會解決你的問題。

0

join()是一個調用o'death。如果一個線程阻塞或卡住,調用它的join()方法可以確保卡住被高效地擴展到調用線程。

如果你有可能逃避它,不要使用join()。特別是不要用它在start()之後直接調用它來等待另一個線程的結果。雙 - 特別是不要在GUI事件處理程序中使用它。