EventBus作为消息总线,通过解耦发布者和订阅者简化事件传递
本文实现一个handler演示如何使用EventBus
定义消息类型对象EventMsg
package com.binfoo.observer.event; /** * 定义消息类型对象 */ public class EventMsg { private String msg; public EventMsg(){ } public EventMsg(String msg){ this.msg = msg; } public String getMsg() { return msg; } @Override public String toString() { return "EventMsg{" + "msg=‘" + msg + ‘\‘‘ + ‘}‘; } public void setMsg(String msg) { this.msg = msg; } }
- 实现Runnable接口的EventHandler,含有成员EventBus,当线程启动时候,进行注册线程本身
package com.binfoo.observer.event; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; public class EventHandler implements Runnable{ public EventBus getEventBus() { return eventBus; } public void setEventBus(EventBus eventBus) { this.eventBus = eventBus; } private EventBus eventBus; public EventHandler(EventBus eventBus){ this.eventBus = eventBus; } @Subscribe @AllowConcurrentEvents public void handler(EventMsg eventMsg){ System.out.println("线程: " + Thread.currentThread().getName()+ " 处理得到消息: " + eventMsg.toString()); } @Override public void run() { eventBus.register(this); System.out.println(Thread.currentThread().getName()); } }
- 进行测试,交替发送不同的消息
package com.binfoo.observer.event; import com.google.common.eventbus.EventBus; public class EventHandlerTest { public static void main(String[] args) { EventMsg msg1 = new EventMsg("中国人民共和国万岁!"); EventMsg msg2 = new EventMsg("世界人民大团结万岁!"); EventMsg msg3= new EventMsg("!!!!!!!!!"); EventHandler eventHandler = new EventHandler(new EventBus()); new Thread(eventHandler).start(); for (int j =0; j<10;j++){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } if (j%2==0){ System.out.println("------" + j); eventHandler.getEventBus().post(msg1); }else if (j%2==1){ System.out.println("======" + j); eventHandler.getEventBus().post(msg2); }else { System.out.println("......." + j); eventHandler.getEventBus().post(msg3); } } } }
- 我们看到结果
-
Thread-1 ------0 线程: main 处理得到消息: EventMsg{msg=‘中国人民共和国万岁!‘} ======1 线程: main 处理得到消息: EventMsg{msg=‘世界人民大团结万岁!‘} ------2 线程: main 处理得到消息: EventMsg{msg=‘中国人民共和国万岁!‘} ======3 线程: main 处理得到消息: EventMsg{msg=‘世界人民大团结万岁!‘} ------4 线程: main 处理得到消息: EventMsg{msg=‘中国人民共和国万岁!‘} ======5 线程: main 处理得到消息: EventMsg{msg=‘世界人民大团结万岁!‘} ------6 线程: main 处理得到消息: EventMsg{msg=‘中国人民共和国万岁!‘} ======7 线程: main 处理得到消息: EventMsg{msg=‘世界人民大团结万岁!‘} ------8 线程: main 处理得到消息: EventMsg{msg=‘中国人民共和国万岁!‘} ======9 线程: main 处理得到消息: EventMsg{msg=‘世界人民大团结万岁!‘} Process finished with exit code 0