java - 使用 Guava 的 EventBus,可以在创建总线的线程上运行订阅者代码吗?

标签 java android multithreading guava

使用 Guava 的 EventBus,我希望能够从后台线程(称为“后台”)发布到更新 UI 的特定线程(在本例中为线程“main”)。我认为以下会起作用,但这会从后台线程调用订阅者代码:

package com.example;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventBusTester {

    private static final Logger log = LoggerFactory.getLogger(EventBusTester.class);

    public static void main(String... args) {
        new EventBusTester().run();
    }

    private void run() {
        log.info("Starting on thread {}.", Thread.currentThread().getName());

        final EventBus eventBus = new AsyncEventBus(MoreExecutors.sameThreadExecutor());
        eventBus.register(this);

        Thread background = new Thread(new Runnable() {
            @Override
            public void run() {
                long now = System.currentTimeMillis();
                eventBus.post(now);
                log.info("Posted {} to UI on thread {}.", now, Thread.currentThread().getName());
            }
        }, "background");
        background.start();
    }

    @Subscribe
    public void updateUi(Long timestamp) {
        log.info("Received {} on UI on thread {}.", timestamp, Thread.currentThread().getName());
    }
}

这将打印以下内容:

02:20:43.519 [main] INFO  com.example.EventBusTester - Starting on thread main.
02:20:43.680 [background] INFO  com.example.EventBusTester - Received 1387848043678 on UI on thread background.
02:20:43.680 [background] INFO  com.example.EventBusTester - Posted 1387848043678 to UI on thread background.

所以我的问题是:

  1. 是否可以做我想做的事,例如使用我不知何故错过的 ExecutorService,或者编写自定义 ExecutorService,或者
  2. 我需要一些其他的库来完成这个吗?例如。 Square 的 Otto(因为我也会在 Android 上使用它)。

不过,我宁愿留在纯 Guava 。

谢谢!

最佳答案

如果您使用 EventBus 实例,则 @Subscribe 方法将在发布事件的同一线程上执行。

如果您想做一些不同的事情,请使用 AsyncEventBus,您可以在其中提供一个 Executor 来定义事件发布时的确切行为。

例如,在 Android 上,要使每个 @Subscribe 方法都在主线程上运行,您可以执行以下操作:

EventBus eventBus = new AsyncEventBus(new Executor() {

    private Handler mHandler;

    @Override
    public void execute(Runnable command) {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        mHandler.post(command);
    }
});

Looper.getMainLooper() 返回应用程序的主循环程序,它位于应用程序的主线程上。

关于java - 使用 Guava 的 EventBus,可以在创建总线的线程上运行订阅者代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753614/

相关文章:

多处理器机器上的 Java 堆和 GC?

Android 在多边形上绘制位图

c# - 停止在线程中播放音乐

java - 防止用户在jsp注销后返回

java - 基本的 MVC 模式和 GUI

java - 用Java读取CSV文件并将值存储在int数组中

android - View.getWidth() 在 onCreate 方法中不起作用?

android - AlarmManager 无法正常工作

c - 读取/接收线程安全 (MSG_PEEK)

我可以知道哪个线程从核心转储文件中更改了全局变量的值吗?