异步数据处理

 后台的异步处理

 把需要处理的数据放入阻塞队列中 

public static BlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
AsyncQueue.queue.put(jsonObject);


然后初始化线程池去执行

public static void init(){
executor = new ThreadPoolExecutor(100, 200, 30*1000,
TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(5000));

log.info("初始化核心线程数量 "+executor.getCorePoolSize());
log.info("初始化最大线程数量 "+executor.getMaximumPoolSize());

executor.execute(new SmsAsyncQueueTake(queue));
}


public static void destroyed(){
executor.shutdown();
}


线程的设计 需要做的事情
public class SmsAsyncQueueTake implements Runnable{

private static Logger log = Logger.getLogger(SmsAsyncQueueTake.class);
private BlockingQueue<JSONObject> queue;

public SmsAsyncQueueTake(BlockingQueue<JSONObject> queue){
this.queue=queue;
}


@Override
public void run() {
while(!Thread.interrupted()){
try {
if(AsyncQueue.executor.getQueue().size()<5000){
JSONObject sms = queue.take();
try {
AsyncQueue.executor.execute(new SmsAsyncService(sms));
} catch (RejectedExecutionException e) {
log.debug("异步线程执行异常:"+e.getMessage());
}

}else{
Thread.sleep(500);
}

} catch (Exception e) {
log.error(e.getMessage());
}
}

}

}




posted @ 2018-06-29 17:54  __Ant  阅读(346)  评论(0编辑  收藏  举报