EventBus入门案例

2018-09-13  本文已影响9人  heyong

## 一、概述

通过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源码

上一篇 下一篇

猜你喜欢

热点阅读