监听器 demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/edc0228/article/details/80937495

记录下监听器demo
这几天学习activemq时,消息的消费者获取到mq里面的数据有两种方式。一种是while(true){mq.take()}通过死循环取数据,但是这种方式很消耗性能。还有一种就是向mq注册一个监听器了。

监听器模型

小需求:模拟mq,实现当有数据新增到mq里面时通知监听器

/**
 * 监听器接口
 * @author JiaJiCheng
 * @date 2018年7月6日
 */
public interface QListener {
    /**
     * 处理方法
     * @param msg
     */
    void onMessage(Object msg);
}


/**
 * 模拟队列
 * @author JiaJiCheng
 * @date 2018年7月6日
 */
public class MyQueue {
    // 无界阻塞队列
    private LinkedBlockingDeque<String> queue = new LinkedBlockingDeque<>();

    // 监听器
    private QListener listener;

    public void setListener(QListener listener) {
        this.listener = listener;
    }

    public void add(String str) {
        if (!StringUtils.isEmpty(str)) {
            queue.add(str);
            if (this.listener != null) {
                listener.onMessage(str);
            }

        }
    }

    public String take() {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

/**
 * 消费者
 * @author JiaJiCheng
 * @date 2018年7月6日
 */
public class Customer {
    public static void main(String[] args) {
    final MyQueue myQueue = new MyQueue();

    // 注册监听器
    myQueue.setListener(new QListener() {

        @Override
        public void onMessage(Object msg) {
            System.out.println("收到消息=" + msg);
        }
    });

    new Thread(new Runnable() {

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                myQueue.add("我是消息" + i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }).start();

    // 原始方式
    // while(true) {
    // String str =myQueue.take();
    // System.out.println(str);
    // }

    }
}

猜你喜欢

转载自blog.csdn.net/edc0228/article/details/80937495