2010-07-19 174 views

回答

4

這應該做你所需要的。它使用已知對象notify()wait()來使該方法本質上同步。 run()中的任何內容都將在UI線程上運行,並在完成後將控制權返回doSomething()。這當然會讓調用線程進入睡眠狀態。

public void doSomething(MyObject thing) { 
    String sync = ""; 
    class DoInBackground implements Runnable { 
     MyObject thing; 
     String sync; 

     public DoInBackground(MyObject thing, String sync) { 
      this.thing = thing; 
      this.sync = sync; 
     } 

     @Override 
     public void run() { 
      synchronized (sync) { 
       methodToDoSomething(thing); //does in background 
       sync.notify(); // alerts previous thread to wake 
      } 
     } 
    } 

    DoInBackground down = new DoInBackground(thing, sync); 
    synchronized (sync) { 
     try { 
      Activity activity = getFromSomewhere(); 
      activity.runOnUiThread(down); 
      sync.wait(); //Blocks until task is completed 
     } catch (InterruptedException e) { 
      Log.e("PlaylistControl", "Error in up vote", e); 
     } 
    } 
} 
+1

我不明白什麼叫一個字符串notify()會做什麼? – 2013-09-23 13:28:52

相關問題