-
ExecutorService executorServer = xxxxxx.getThreadPool();
-
Future future = executorServer.submit(new xxxxxxx(Param, funcId));
-
Object obj = future.get(100, TimeUnit.MILLISECONDS); //总超时时间设置
其中,future.get是从开始进行get方法时进行计算的时间,非future生成开始计算的,即什么时候get什么时候开始计时。
线程池从生成线程,如果核心线程不为0,则有任务时一直生成核心线程,直至到核心线程,之后开始方队列中,最后任务多就开始开辟新线程到最大线程数。
执行任务时,首先线程池开辟线程,之后 线程start( execute方法->addWorker-->t.start())后开始执行call方法。但从.start 到 执行call方法,需要CPU进行线程的上下文切换。 可以根据重写的
ThreadPoolExecutor方法来跟踪。
在高并发下,如果线程池不加 executorServer.prestartAllCoreThreads();
则在线程为1500的并发下,即新创建线程start状态为NEW,真正运行时为RUNNABLE(start后),到call真正的调用会耗时,因CPU切换。
如不加,则会有12-160多ms的消耗,
如果加上prestartAllCoreThreads()则性能会好很多,最大从start到call才3ms.
同时,如使用hutool-all-5.3.8.jar的ThreadUtil.execAsyn方法效果也比较好,但没有restartAllCoreThreads()这个好,测试效果有9-14ms的消耗。
-
public static ThreadPoolExecutor getThreadPool() {
-
if (executorServer == null || executorServer.isShutdown() || executorServer.isTerminated()) {
-
synchronized (JzPreCheckUtil.class) {
-
if (executorServer == null || executorServer.isShutdown() || executorServer.isTerminated()) {
-
XxxConfig.isJzPrecheckEnabled(); //加载相关配置
-
log.info("corePoolSize="+XxxConfig.corePoolSize+" maximumPoolSize="+XxxConfig.maximumPoolSize+" keepAliveTime="+XxxConfig.keepAliveTime);
-
ThreadFactory threadFactory = new ThreadFactory() {
-
@Override
-
public Thread newThread(Runnable r) {
-
long t1=System.currentTimeMillis();
-
String threadName="jzThreadPool" + r.hashCode();
-
Thread newThread=new Thread(r, threadName);
-
long t2=System.currentTimeMillis();
-
log.info("创建线程="+threadName+" t1="+t1+" t2="+t2+" 时间差="+(t2-t1));
-
return newThread;
-
}
-
};
-
executorServer = new ThreadPoolExecutor(XxxConfig.corePoolSize, XxxConfig.maximumPoolSize, XxxConfig.keepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),threadFactory);
-
executorServer.prestartAllCoreThreads();
-
log.info("prestartAllCoreThreads 之后="+executorServer.getQueue().size()+" 线程活着的数量="+executorServer.getActiveCount()+
-
" 核心线程="+executorServer.getCorePoolSize()+" 最大线程="+executorServer.getMaximumPoolSize()+
-
" 线程数="+executorServer.getPoolSize());
-
}
-
}
-
}
-
log.info("queue 长度 后="+executorServer.getQueue().size()+" 线程活着的数量="+executorServer.getActiveCount()+
-
" 核心线程="+executorServer.getCorePoolSize()+" 最大线程="+executorServer.getMaximumPoolSize()+
-
" 线程数="+executorServer.getPoolSize());
-
return executorServer;
-
}
-
@Override
-
public Object call() throws Exception {
-
xxx
-
return out;
-
}
重写
ThreadPoolExecutor参考:
-
package com.stock.framework.precheck.test2;
-
import com.stock.framework.jzprecheck.JzConfig;
-
import org.slf4j.Logger;
-
import java.lang.reflect.Constructor;
-
import java.lang.reflect.Field;
-
import java.lang.reflect.InvocationTargetException;
-
import java.lang.reflect.