Android:后台线程可能会阻塞,直到 UI 线程完成操作?

发布于 2024-09-10 16:35:51 字数 116 浏览 10 评论 0原文

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

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

Is it possible for a background thread to enqueue a message to the main UI thread's handler and block until that message has been serviced?

The context for this is that I would like my remote service to service each published operation off its main UI thread, instead of the threadpool thread from which it received the IPC request.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘心安 2024-09-17 16:35:51

这应该可以满足您的需要。它使用 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);
        }
    }
}

This should do what you need. It uses notify() and wait() with a known object to make this method synchronous in nature. Anything inside of run() will run on the UI thread and will return control to doSomething() once finished. This will of course put the calling thread to sleep.

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);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文