我正在用 Java 设计一个独立的多线程应用程序。 我正在尝试为他的项目选择最佳的事件处理解决方案。
我有 1-3 个线程生成事件(例如 comm 线程完成文件上传),而其他线程可能想要注册以接收有关此事件的通知。 我希望事件生成和事件监听尽可能不耦合。
你有什么建议?
最佳答案
使用 event bus .
An event bus can be thought of as a replacement for the observer pattern, where in the observer pattern, each component is observing an observable directly. In the event bus pattern, each component simply subscribes to the event bus and waits for its event notification methods to be invoked when interesting events have occurred. In this way, an event bus can be thought of like the observer pattern with an extra layer of decoupling.
这是一个不错的 presentation关于在 GWT 中使用事件总线。它应该让您对好处有一个很好的了解(而且它也很有趣)。
编辑
第一个链接主要是作为示例给出的。自己实现符合您需求的类似东西并不难。
关于java - 多线程应用程序中的事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788159/