开发中,经常会碰到有时间为了性能而编写线程做异步请求,
这是公用线程池,如果需要用完就删除,建议不要使用线程池,直接手动 new thread 创建线程去操作
// 线程池管理类(饿汉模式加载)
public ThreadPoolExecutor(
int corePoolSize, // 核心线程数,即最小线程数
int maximumPoolSize, // 最大线程数,只有当workQueue队列填满时才会创建多于corePoolSize的线程
long keepAliveTime, TimeUnit unit, // 非核心线程的空闲时间超过keepAliveTime就会被自动终止回收,corePoolSize=maxPoolSize时,keepAliveTime参数也就不起作用了(因为不存在非核心线程)
BlockingQueue<Runnable> workQueue, // 任务的排队队列
ThreadFactory threadFactory, // 新线程的产生方式
RejectedExecutionHandler handler) // 拒绝策略,取值有AbortPolicy、CallerRunsPolicy、DiscardOldestPolicy、DiscardPolicy
)
public class CreateThreadPoolUtil {
// 最原始的方式创建线程池
private static final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
8, 32, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(128), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
public static ThreadPoolExecutor getInstance() {
return poolExecutor;
}
}
public class TestTransactionalServiceImpl implements TestTransactionalService {
public void testTransactional() throws ExecutionException, InterruptedException {
int inter = 3;
ThreadPoolExecutor poolExecutor = CreateThreadPoolUtil.getInstance();
FutureTask[] integerFuture = new FutureTask[inter];
for (int i = 0; i < inter; i++) {
int finalI = i + 1;
integerFuture[i] = new FutureTask<>(() -> {
return new TransactionCallback<String>() {
@Override
public String doInTransaction(TransactionStatus transactionStatus) {
System.out.println("多线程运行了---" + finalI);
return "业务执行成功";
}
};
});
poolExecutor.execute(integerFuture[i]);
}
for (int i = 0; i < inter; i++) {
System.out.println("integerFuture返回结果 = " + i + "==" + integerFuture[i].get());
}
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
System.out.println("线程总数为 = " + bean.getThreadCount());
}
}