-
package com.express.otp.ffs.commonorginfo.utils;
import net.ytoframework.kernel.core.consts.SysErrorConsts; import
net.ytoframework.kernel.core.exception.YtoException; import
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.ArrayList; import java.util.List; import
java.util.concurrent.*;/** * 并行执行器 *
- */
public class ConcurrentExecutor {
private static ThreadPoolTaskExecutor threadPoolTaskExecutor;
static {
threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setMaxPoolSize(10);
threadPoolTaskExecutor.setQueueCapacity(50);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolTaskExecutor.setThreadNamePrefix("YtoExecutor-");
threadPoolTaskExecutor.initialize();
}
/**
* 执行一组有返回值的任务
* @param callableList 任务列表
* @param timeout 任务超时时间,单位毫秒
* @param <T>
* @return
*/
public static <T> List<T> execute(List<Callable<T>> callableList,
long timeout) {
if (callableList == null || callableList.isEmpty()) {
return null;
}
List<T> resultList = new ArrayList<>();
List<Future<T>> futureList = new ArrayList<>();
for (Callable<T> callable : callableList) {
Future<T> future = threadPoolTaskExecutor.submit(callable);
futureList.add(future);
}
for (Future<T> future : futureList) {
try {
T result = future.get(timeout, TimeUnit.MILLISECONDS);
if (result != null) {
resultList.add(result);
}
} catch (InterruptedException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
} catch (ExecutionException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
} catch (TimeoutException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
}
}
return resultList;
}
/**
* 执行一组没有返回值的任务
*
* @param runnableList 任务列表
* @param timeout 任务超时时间,单位毫秒
*/
public static void submit(List<Runnable> runnableList,
long timeout,
ThreadPoolTaskExecutor threadPoolTaskExecutor) {
if (runnableList == null || runnableList.isEmpty()) {
return;
}
List<Future<?>> futureList = new ArrayList<>();
for (Runnable runnable : runnableList) {
Future future = threadPoolTaskExecutor.submit(runnable);
}
for (Future<?> future : futureList) {
try {
future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
} catch (InterruptedException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
} catch (ExecutionException e) {
e.printStackTrace();
throw new YtoException(SysErrorConsts.SYS_ERROR_CODE, "多线程执行异常");
}
}
} }