多线程 callable /future 实现伪代码:
int index=1;
int pagSize=1000;
MagicMirrorPictureBaseInfoDao pictureBaseInfoDao=new MagicMirrorPictureBaseInfoDao();
List<MagicMirrorPictureBaseInfo> pictureBaseInfoList=pictureBaseInfoDao.queryImageInfo(index, pagSize);
List<Future<Boolean>> taskResultList = new ArrayList<>();
while (pictureBaseInfoList !=null && !pictureBaseInfoList.isEmpty() && !ProductImageQrcodeWorker.shouldStrop()){
for (MagicMirrorPictureBaseInfo baseInfo:pictureBaseInfoList){
if(ProductImageQrcodeWorker.shouldStrop()){
break;
}
ImageQrcodeTask task=new ImageQrcodeTask(baseInfo);
Future<Boolean> taskResult= BusinessTaskPool.getInstance().getThreadPoolTaskExecutor().submit(task);
taskResultList.add(taskResult);
if (taskResultList.size()>5){
checkResultList(taskResultList);
taskResultList=new ArrayList<>();
}
}
checkResultList(taskResultList);
index ++;
pictureBaseInfoList=pictureBaseInfoDao.queryImageInfo(index, pagSize);
}
/**
* 多线程check任务完成(返回值为boolean)
* @param taskResultList
*/
public void checkResultList(List<Future<Boolean>> taskResultList) {
if (!taskResultList.isEmpty()) {
for (Future<Boolean> f : taskResultList) {
try {
f.get();
} catch (Exception e) {
clog.warn(CLOG_TITLE,"多线程任务失败");
}
}
}
}
/**
- 有返回值的
*/
private List waitTaskComplete(List<Future> taskResultList){
List list=new ArrayList<>();
for(Future tr : taskResultList){
try {
list.add(tr.get());
} catch (Exception e) {
cLogger.warn(TITLE,e);
}
}
return list;
}
/**
-
线程池
-
@date 2017/11/15
*/
public final class BusinessTaskPool {
private static final Integer POOL_SIZE = 20;
private static final Integer MAX_POOL_SIZE = 100;
private static final Integer QUEUE_CAPACITY = 100;
private static final Integer KEEP_ALIVE_SECONDS = 5;
private static BusinessTaskPool businessTaskPool = new BusinessTaskPool();
private ThreadPoolTaskExecutor poolTaskExecutor;private BusinessTaskPool(){
poolTaskExecutor = new ThreadPoolTaskExecutor();
poolTaskExecutor.setCorePoolSize(POOL_SIZE);
poolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
poolTaskExecutor.setQueueCapacity(QUEUE_CAPACITY);
poolTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
poolTaskExecutor.initialize();
}/**
- 设置线程池数量
- @param poolSize
*/
public void setPoolSize(Integer poolSize){
poolTaskExecutor.setCorePoolSize(poolSize);
}
public static BusinessTaskPool getInstance(){
return businessTaskPool;
}public ThreadPoolTaskExecutor getThreadPoolTaskExecutor(){
return this.poolTaskExecutor;
}
}