2010-07-19 180 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

相关问题