安卓:后台线程是否可以阻塞,直到UI线程完成操作?

6

后台线程是否可以将消息排队到主UI线程的处理程序,并阻塞直到该消息已被处理?

这个问题的背景是,我希望我的远程服务在其主UI线程之外为每个发布的操作提供服务,而不是从它接收IPC请求的线程池线程。

1个回答

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);
        }
    }
}

1
我不明白在字符串上调用notify()会做什么? - David Doria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接