IOT项目,考虑并发,加入多线程,使用线程池
BEFORE:
// 设置回调函数 client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { System.out.println("connectionLost"); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println(message); //若收到信息就走处理信息的方法,这里直接调方法 msgHandlerService.msgHandle(topic,message); } @Override public void deliveryComplete(IMqttDeliveryToken token) { System.out.println("deliveryComplete---------"+ token.isComplete()); } });
AFTER:
//创建线程池对象
// CachedThreadPool 同步队列,这个队列类似于一个接力棒,入队出队必须同时传递,因为CachedThreadPool线程创建无限制,不会有队列等待,所以使用SynchronousQueue;
//适用场景:快速处理大量耗时较短的任务
ThreadPoolExecutor executor = new ThreadPoolExecutor(4,Integer.MAX_VALUE,20, TimeUnit.SECONDS,new SynchronousQueue<>());
----------------------------------------------------------------------------------
// 设置回调函数 client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { System.out.println("connectionLost"); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println(message);
MyThread task = new MyThread(msgHandler,topic,message);
//这里 execute 比较coreThread和当前threadCount 0.新增线程执行任务addWork 1.插入任务队列 executor.execute(task); System.out.println("当前线程池大小:"+executor.getPoolSize()+" 当前活跃线程:"+executor.getActiveCount()); System.out.println("收到任务:"+executor.getTaskCount()+" 完成任务:"+executor.getCompletedTaskCount()+" 剩余任务:"+(executor.getTaskCount()-executor.getCompletedTaskCount())); } @Override public void deliveryComplete(IMqttDeliveryToken token) { System.out.println("deliveryComplete---------"+ token.isComplete()); } });