美文网首页
EventBus入门案例

EventBus入门案例

作者: heyong | 来源:发表于2018-09-13 20:36 被阅读9次

## 一、概述

通过EventBus可以快速的实现发布订阅模式,EventBus提供了两种模式

同步事件模式:同步事件模式下,事件的触发和事件的处理在同一个线程中同步处理

异步事件模式:异步事件模式下,事件的触发和事件的处理在不同的线程中,事件的处理在一个线程池中

二、入门案例

(一)同步事件模式

  • 定义事件
public class ItemEvent {
    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "ItemEvent{" + "title='" + title + '\'' + '}';
    }
}
  • 事件处理器
public class MessageListener {
    @Subscribe
    public void process(ItemEvent msg) {
        System.out.println(Thread.currentThread().getName() + " : " + msg);
    }
}
  • 事件发布
public class SyncMain {
    public static void main(String[] args) {
        EventBus eventBus = new EventBus();
        eventBus.register(new MessageListener());
        
        ItemEvent itemEvent = new ItemEvent();
        itemEvent.setTitle(Thread.currentThread().getName());
        for (int i = 0; i < 100; i++) {
            eventBus.post(itemEvent);
        }
    }
}
  • 输出结果
main : ItemEvent{title='main'}
main : ItemEvent{title='main'}
...........

总结,从上面的输出接口可以看出,事件的触发和事件的处理都是在同一个线程中。

(二)异步事件模式

  • 定义事件

     事件定义和同步事件模式下的定义一致
    
  • 定义事件处理器

public class MessageListener {
    @AllowConcurrentEvents
    @Subscribe
    public void process(ItemEvent msg) {
        System.out.println(Thread.currentThread().getName() + " : " + msg);
    }
}
  • 事件发布
public class AsyncMain {
    private static final int CORE_SIZE = Runtime.getRuntime().availableProcessors();
    private static final int ALIVE_TIME = 30;
    private static final int CACHE_SIZE = 1000;

    public static void main(String[] args) throws InterruptedException {
        AsyncEventBus eventBus = new AsyncEventBus(new ThreadPoolExecutor(CORE_SIZE, CACHE_SIZE << 1, ALIVE_TIME, TimeUnit.MINUTES, new ArrayBlockingQueue(CACHE_SIZE)));
        eventBus.register(new MessageListener());
        ItemEvent itemEvent = new ItemEvent();
        itemEvent.setTitle(Thread.currentThread().getName());
        for (int i = 0; i < 1000; i++) {
            eventBus.post(itemEvent);
        }
    }
}
  • 运行结果
pool-1-thread-1 : ItemEvent{title='main'}
pool-1-thread-2 : ItemEvent{title='main'}
pool-1-thread-3 : ItemEvent{title='main'}
pool-1-thread-4 : ItemEvent{title='main'}
pool-1-thread-5 : ItemEvent{title='main'}
pool-1-thread-6 : ItemEvent{title='main'}
pool-1-thread-7 : ItemEvent{title='main'}
pool-1-thread-8 : ItemEvent{title='main'}
pool-1-thread-8 : ItemEvent{title='main'}
pool-1-thread-3 : ItemEvent{title='main'}

......................
  • 总结
    从上面的结果可以看出,异步事件模式下,事件的触发和处理是在不同的线程中的,事件的处理是在单独的线程池中进行处理

三、结语

本来主要讲了EventBus的入门案例,同步事件模型和异步事件模型的之间的区别,下章将分析EventBus源码

相关文章

网友评论

      本文标题:EventBus入门案例

      本文链接:https://www.haomeiwen.com/subject/bfpggftx.html