package com.example.demo.thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Service
public class PushProcessServiceImpl{
private final static Logger logger = LoggerFactory.getLogger(PushProcessServiceImpl.class);
private static final Integer LIMIT = 5000;
private static final Integer CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
private static final Integer MAXIMUM_POOl_SIZE = CORE_POOL_SIZE;
ThreadPoolExecutor pool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOl_SIZE * 2, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(Integer.MAX_VALUE));
public void pushData() throws ExecutionException, InterruptedException {
int count = 0;
Integer total = 100000;
logger.info("未推送数据条数:{}", total);
int threadCount = LIMIT;
int num = total % threadCount == 0 ? total / threadCount : total / threadCount + 1;
logger.info("要经过的轮数:{}, 每轮发送 {}条", num, threadCount);
int totalSuccessCount = 0;
for (int i = 0; i < num; i++) {
List<Future<Integer>> futureList = new ArrayList<>(32);
int start = count * LIMIT;
count++;
Future<Integer> future = pool.submit(new PushDataTask(start, LIMIT, i));
futureList.add(future);
}
for (Future<Integer> f : futureList) {
totalSuccessCount = totalSuccessCount + f.get();
}
logger.info("推送数据完成,需推送数据:{},推送成功:{}", total, totalSuccessCount);
}
class PushDataTask implements Callable<Integer> {
int start;
int limit;
PushDataTask(int start, int limit, int threadNo) {
this.start = start;
this.limit = limit;
}
@Override
public Integer call() throws Exception {
Thread.currentThread().setName("Thread" + start);
int count = 0;
List<Integer> pushProcessList = getId(start, limit);
if (CollectionUtils.isEmpty(pushProcessList)) {
return count;
}
logger.info("推送区间:[{},{}]数据", start, start + limit);
for (Integer process : pushProcessList) {
if (process>=0) {
count++;
} else {
}
}
logger.info("推送区间[{},{}]数据,推送成功{}条!", start, start + limit, count);
return count;
}
}
private List<Integer> getId(int start,int limit){
List<Integer> list = new LinkedList<>();
for (int i = 0; i < limit; i++) {
start = start + i ;
list.add(start);
}
return list;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
PushProcessServiceImpl p = new PushProcessServiceImpl();
p.pushData();
}
}