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

zer*_*lus 6 multithreading android ui-thread

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

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

Rya*_*yan 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)