1.现场池工厂类
public class ThreadFactoryBuilder implements ThreadFactory {
private String name;
private int counter;
public ThreadFactoryBuilder(String name) {
this.name = name;
counter = 1;
}
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(runnable, name);
thread.setName("ThreadFactoryBuilder_" + name + "_" + counter);
return thread;
}
}
2.线程池工具类
public class ThreadPool {
private static ThreadPool threadPool;
/**
* java线程池
*/
private ThreadPoolExecutor threadPoolExecutor;
/**
* 最大线程数
*/
private final static int MAX_POOL_COUNTS = 20;
/**
* 线程存活时间
*/
private final static long ALIVETIME = 200L;
/**
* 核心线程数
*/
private final static int CORE_POOL_SIZE = 20;
/**
* 线程池缓存队列
*/
private BlockingQueue<Runnable> mWorkQueue = new ArrayBlockingQueue<>(CORE_POOL_SIZE);
private ThreadFactory threadFactory = new ThreadFactoryBuilder("ThreadPool");
private ThreadPool() {
//初始化线程池 核心线程数为20,最大线程数30,线程存活200L,线程队列mWorkQueue,
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_COUNTS, ALIVETIME, TimeUnit.SECONDS, mWorkQueue, threadFactory);
}
public static ThreadPool getInstantiation() {
if (threadPool == null) {
threadPool = new ThreadPool();
}
return threadPool;
}
/**
* 为线程池添加任务
* @param runnable
*/
public void addTask(Runnable runnable) {
if (runnable == null) {
throw new NullPointerException("addTask(Runnable runnable)传入参数为空");
}
if (threadPoolExecutor != null && threadPoolExecutor.getActiveCount() < MAX_POOL_COUNTS) {
threadPoolExecutor.execute(runnable);
}
}
public <T> void submitTask(FutureTask<T> futureTask){
if (futureTask == null) {
throw new NullPointerException("submitTask(FutureTask futureTask)传入参数为空");
}
if (threadPoolExecutor != null && threadPoolExecutor.getActiveCount() < MAX_POOL_COUNTS) {
threadPoolExecutor.submit(futureTask);
}
}
public void stopThreadPool() {
if (threadPoolExecutor != null) {
threadPoolExecutor.shutdown();
threadPoolExecutor = null;
}
}
}
3.调用线程池工具类
FutureTask<ObjectResult<Business>> futureTask = new FutureTask<>(() -> {
//...处理业务
ObjectResult<Business> result = new ObjectResult<>();
result.setData(idCard);
return result;
});
try {
ThreadPool.getInstantiation().submitTask(futureTask);
result = futureTask.get();
} catch (Exception e) {
e.printStackTrace();
}