工作中常常遇到使用线程池的场景,写一个工具类,方便使用
public class ThreadPoolUtils {
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
16,
16,
30,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(2048),
new ThreadPoolExecutor.CallerRunsPolicy());
//执行任务
public static void execute(Runnable command){
executor.execute(command);
}
//有返回值
public static <T> Future<T> submit(Callable<T> task){
return executor.submit(task);
}
//关闭线程池
public static void shutdown(){
if (executor != null){
executor.shutdown();
}
}
}
用法
ThreadPoolUtils.execute(() ->{
//执行具体逻辑
});
ThreadPoolUtils.submit(() -> {
//执行具体逻辑,需要有返回值;
return new JSONObject();
});