public class ThreadPoolUtils implements InitializingBean {
ThreadPoolExecutor executor;
int threadSize;
int maximumPoolSize;
long keepAliveTime;
int maxQueueSize;
@Override
public void afterPropertiesSet() throws Exception {
BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(maxQueueSize, true);
executor = new ThreadPoolExecutor(threadSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, taskQueue);
}
public class CreateOrderInvoker implements Callable<String> {
private OrderService service;
private OrderParam param;
private CountDownLatch countDownLatch;
public CreateOrderInvoker(OrderService service, OrderParam param) {
this.service = service;
this.param = param;
}
@Override
public String call() throws Exception {
String value= service.createOrder(param);
countDownLatch.countDown();
return value;
}
public void test(){
List<FutureTask<String>> futureTasks = new ArrayList<FutureTask<String>>(10);
ThreadPoolUtils poolUtils = new ThreadPoolUtils();
for (int i = 0; i < 10; i++) {
CreateOrderInvoker invoker = new CreateOrderInvoker(null,null);
FutureTask<String> futureTask = new FutureTask<String>(invoker);
try {
poolUtils.getExecutor().execute(futureTask);
futureTasks.add(futureTask);
} catch (Exception e) {
}
}
// 3 获取各个createPayOrder的接口
boolean concurrentResult = false;
try {
concurrentResult = countDownLatch.await(25, TimeUnit.SECONDS);//多线程执行设定超时时间
if (concurrentResult) {
System.out.println("批量创建成功,尚未返回的创建结果的有{}个"+ countDownLatch.getCount());
} else {
System.out.println("批量创建有超时,尚未返回创建结果的有{}个。参数是:{}", countDownLatch.getCount(), JSON.toJSONString(param));
}
} catch (Throwable e) {
}
poolUtils.getExecutor().submit(new Runnable() {
@Override
public void run() {
System.out.println("执行具体的任务");
}
});
}
}