多线程异步处理示例

public class UserTrackTask {

 

private static Logger logger = LoggerFactory.getLogger(UserTrackTask.class);

 

private static AtomicBoolean init = new AtomicBoolean(false);

 

private static AtomicBoolean running = new AtomicBoolean(false);

 

private static ExecutorService executorService = Executors.newFixedThreadPool(1);

 

private static BlockingQueue<UserTrackModel> queue = new LinkedBlockingQueue<UserTrackModel>();

 

private static UserTrackService userTrackService;

 

private static void init(){

if(init.get()){

return;

}

synchronized (init) {

if(init.get()){

return;

}

if(userTrackService == null){

userTrackService = SpringContextUtil.getBean(UserTrackService.class);

}

if(!running.get()){

start();

}

init.set(true);

}

}

 

private static void start(){

if(running.get()){

return;

}

running.set(true);

executorService.execute(new Runnable() {

 

@Override

public void run() {

try {

while (running.get()) {

UserTrackModel track = null;

try {

track = queue.take();

if(track == null){

continue;

}

userTrackService.add(track);

} catch (Exception e) {

logger.error("add user track due to error",e);

}

}

} catch (Exception e) {

logger.error("proccess creditlog thread is exit!!!!");

}

}

});

}

 

public static void save(String uid,String openId,String domain,String url,long time){

UserTrackModel track = new UserTrackModel(uid,openId,domain,url,time);

boolean bool = offer(track);

if(!bool){

logger.error("put creditlog queue due to fail. createlog=[{},{},{},{},{}]",uid,openId,domain,url,time);

}

}

 

private static boolean offer(UserTrackModel track) {

if(!init.get()){

init();

}

return queue.offer(track);

}

}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014411966/article/details/52367319
上一篇windows端口占用查看
下一篇以流的形式将文件写入页面,直接下载
想对作者说点什么? 我来说一句

Java多线程实现异步调用实例

2014年09月18日 6KB 下载

没有更多推荐了,返回首页

关闭
关闭