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