gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:41 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com