Android:在UI线程完成操作之前,后台线程可能会阻塞吗?

时间:2010-07-19 22:26:20

标签: android multithreading ui-thread

后台线程是否有可能将消息排入主UI线程的处理程序并阻塞,直到该消息得到服务为止?

这个上下文是我希望我的远程服务从其主UI线程服务每个已发布的操作,而不是从它接收IPC请求的线程池线程。

1 个答案:

答案 0 :(得分:5)

这应该做你需要的。它使用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);
        }
    }
}