我正在使用 Guava 事件总线。我有一个类似服务器的对象,它应该一直运行,监听要发布到 b us 的事件。所以在 junit 测试中(MyObject 是被测类),我在自己的线程中创建它来模拟它并防止阻塞:
@Test
public void test() {
EventBus eventBus = new EventBus();
Thread thread= new Thread() {
@Override
public void run()
{
logger.debug("Creating new thread");
MyObject myObject = new MyObject(eventBus);
}
};
thread.start();
...
}
一切都很好,myObject 是在它自己的线程 Thread1 中创建的。然后,我在测试中将事件发布到事件总线:
eventBus.post(triggerObject);
我发现奇怪的是,MyObject 类中我订阅的方法中的所有操作/日志记录再次在主线程中执行。 myObject 等待来自某些其他部分的响应,这会阻止我的测试,因为它在主线程中。为什么会这样? EventBus 或 Java 线程是我做错了什么吗?
最佳答案
好吧,除了创建一个最终在堆中结束(在线程之间共享)的对象外,您在创建的线程中什么都不做,但是由于对它的引用在运行后不会维护,因此它也会丢失。
myObject
中的 @Subscribe
方法是在调用 eventBus.post(event);
的同一线程中调用的,而不是在线程中调用的创建了 myObject
。
The weird thing I am finding is that all the actions/logging from my subscribed method inside of MyObject class are executing in the main thread again
如果您的 MyObject
类有一个 @Subscribe
方法,那么为什么它在构造函数中需要一个 EventBus 实例?你可能想要
MyObject myObject = new MyObject();
eventBus.register(myObject);`
代替 MyObject myObject = new MyObject(eventBus);
关于Java 多线程与 Guava EventBus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25371451/