簡體   English   中英

如何停止當前線程,直到其他線程完成執行?

[英]How to stop the current thread till other thread complete its execution?

這是我的問題...

 public static String response = "";   

'

 public static String sendDataToServer(String data)
  {
    new Thread()  
    {
     public void run()
     {
     //sending data to server
     response = httpClient.execute(httppost, new BasicResponseHandler()).trim();
    }

    } .start();   

   return response;

  }

當我調用此方法時,我將得到空字符串作為響應。

String res = sendDataToServer("my_data");  //res is always empty string
 //...XXXXXXX code after calling the method 

並且總是在完成sendDataToServer()方法執行之前執行XXXXX代碼。 為什么res總是空的? 如何獲得正確的響應字符串? 在執行sendDataServer()方法之前,如何停止執行XXXX代碼? 謝謝。

你可以做:

Thread t = new Thread() {
    public void run() {
        //sending data to server
        response =
              httpClient.execute(httppost, new BasicResponseHandler()).trim();
    }
 };
 t.start();
 t.join();

這樣,您將等到線程完成並且jsut然后繼續。

但是,請記住,在Android中等待線程完成很危險,尤其是在UI線程(即主線程)中。 但是,我假定此線程不在UI線程中,因為否則AsyncTask會是更好的解決方案(並且更加本地化)。

您可以使用join()等待線程,但是由於您使用了線程,因此下面的操作是相同的。

public static String sendDataToServer(String data) {
     //sending data to server
     return httpClient.execute(httppost, new BasicResponseHandler()).trim();
}

您可以使用CountDownLatch來同步線程執行。 正如文檔中所述,CountDownLatch允許一個或多個線程等待,直到在其他線程中執行的一組操作完成。 如果以sendDataToServer開頭的線程是UI或主線程,那么這當然會導致應用程序響應出現問題。 給出更多細節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM