5
后台线程是否可能将消息排入主UI线程的处理程序并阻塞,直到该消息已被服务?Android:后台线程可能会阻塞,直到UI线程完成操作?
对此的上下文是,我希望我的远程服务将每个已发布的操作从其主UI线程中取代,而不是从其接收到IPC请求的线程池线程。
后台线程是否可能将消息排入主UI线程的处理程序并阻塞,直到该消息已被服务?Android:后台线程可能会阻塞,直到UI线程完成操作?
对此的上下文是,我希望我的远程服务将每个已发布的操作从其主UI线程中取代,而不是从其接收到IPC请求的线程池线程。
这应该做你所需要的。它使用已知对象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);
}
}
}
我不明白什么叫一个字符串notify()会做什么? – 2013-09-23 13:28:52