关闭

多线程异步处理示例

85人阅读 评论(0) 收藏 举报
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);

}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13099次
    • 积分:252
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:6篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论