前言: 随着信息技术的进步,各行各业对数据价值的重视程度急剧上升,越来越多的数据被分门别类地积聚下来,对数据库的并发要求越来越高,即同一时间点的数据请求越来越多,对实时性的要求也越来越高。实时性其实是不经过批量排队的高并发实时请求的代名词,同一时间的请求量和请求的处理速度直接决定了并发度:
1.优化的代码
//参数初始化
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//获取cpu核心数:
private static final int getCpuCount = Runtime.getRuntime().availableProcessors();
//核心线程数量大小
private static final int corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));
//线程池最大容纳线程数
private static final int maximumPoolSize = CPU_COUNT * 2 + 1;
//线程空闲后的存活时长
private static final int keepAliveTime = 30;
//任务过多后,存储任务的一个阻塞队列
BlockingQueue<Runnable> workQueue = new SynchronousQueue<>();
//线程的创建工厂
ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AdvacnedAsyncTask #" + mCount.getAndIncrement());
}
};
//线程池任务满载后采取的任务拒绝策略
RejectedExecutionHandler rejectHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
//线程池对象,创建线程
ThreadPoolExecutor mExecute = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
workQueue,
threadFactory,
rejectHandler
);
2.具体实现:
@Test
public void test2() throws InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS");
// 有界队列
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5);
// 放弃拒绝的任务并抛出异常
RejectedExecutionHandler abortPolicyHandler = new ThreadPoolExecutor.AbortPolicy();
RejectedExecutionHandler discardPolicyHandler = new ThreadPoolExecutor.DiscardPolicy();
ThreadPoolExecutor threadPool =
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, discardPolicyHandler);
long start = System.currentTimeMillis();
System.out.println("开始时间:"+formatter.format(new Date()));
for (int i = 0; i < 10000; i++) {
sta(i);
}
System.out.println("队列任务数" + threadPool.getQueue().size());
System.out.println("线程池数" + threadPool.getPoolSize());
System.out.println("cpu核数:"+corePoolSize);
System.out.println("核心线程数量大小:"+getCpuCount);
System.out.println("线程池最大容纳线程数:"+maximumPoolSize);
System.out.println("结束时间:"+formatter.format(new Date()));
}
public void sta(int i){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS");
System.out.println(formatter.format(new Date()) + ": Thread ID :" + Thread.currentThread().getId()+"名字:"+Thread.currentThread().getName()+i);
}
本文探讨了在高并发环境下优化线程池的方法,通过调整核心线程数、最大线程数等参数,结合阻塞队列和任务拒绝策略,提升系统处理能力。实测案例展示了线程池在高负载下的表现。
419

被折叠的 条评论
为什么被折叠?



