使用java 线程计数器进行多个HTTP请求同时调用处理
import java.util.concurrent.CountDownLatch;
public void executeUserList(Date startDate , Date endDate){
logger.info("定时任务:aa 任务--->开始" + sd.format(new Date()));long start1 = System.currentTimeMillis();
String start = sd1.format(startDate);
String end = sd1.format(endDate);
start = StringUtil.getAddOneTime(start);
end = StringUtil.getAddOneTime(end);
try {
ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
CountDownLatch countDownLatch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
UserInfoRunnable userInfoRunnable = new AVBetRunnable(countDownLatch,URIUtil.encodeQuery(start), URIUtil.encodeQuery(end), avBetsMapper,i+1);
executor.execute(avBetRunnable);
}
countDownLatch.await();
executor.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
long end1 = System.currentTimeMillis();
logger.info("定时任务: aa 任务--->结束" + sd.format(new Date())+" 定时插入耗时:"+(end1-start1));
}
package com.cc.dd.service.impl;
import org.apache.log4j.Logger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class UserInfoRunnable implements Runnable {
private static final String date_format = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
private String startDate ;
private String endDate ;
private CountDownLatch countDownLatch ;
public UserInfoRunnable(CountDownLatch countDownLatch,String startDate, String endDate){
this.startDate = startDate ;
this.endDate = endDate ;
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
List<userInfo> userList = userService.getUserList(startDate,endDate);
try {
if(list!=null) {
for (userInfo user : list) {
userList.add(user);
}
}
if (userList.size() > 0) {
userInfoMapper.replaceuserInfo(userList);
}
} catch (Exception e) {
logger.error("异常消息:"+e);
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
}