根据CPU核数合理设置线程池大小
一般來(lái)說(shuō)池中總線程數(shù)是核心池線程數(shù)量?jī)杀?#xff0c;只要確保當(dāng)核心池有線程停止時(shí),核心池外能有線程進(jìn)入核心池即可。??
我們所需要關(guān)心的主要是核心池線程的數(shù)量該如何設(shè)置。
自定義線程池代碼
package com.lc.concurrent; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;public class MyThreadPoolExecutor {//最大可用的CPU核數(shù)public static final int PROCESSORS=Runtime.getRuntime().availableProcessors();//線程最大的空閑存活時(shí)間,單位為秒public static final int KEEPALIVETIME=60;//任務(wù)緩存隊(duì)列長(zhǎng)度public static final int BLOCKINGQUEUE_LENGTH=500;public ThreadPoolExecutor createThreadPool(){return new ThreadPoolExecutor(PROCESSORS * 2,PROCESSORS * 4,KEEPALIVETIME,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(BLOCKINGQUEUE_LENGTH));} }
線程中的任務(wù)最終是交給CPU的線程去處理的,而CPU可同時(shí)處理線程數(shù)量大部分是CPU核數(shù)的兩倍,運(yùn)行環(huán)境中CPU
的核數(shù)我們可以通過(guò)Runtime.getRuntime().availableProcessors()這個(gè)方法而獲取。理論上來(lái)說(shuō)核心池線程數(shù)量應(yīng)該為
Runtime.getRuntime().availableProcessors()*2,那么結(jié)果是否符合我們的預(yù)期呢,可以來(lái)測(cè)試一下(本次測(cè)試測(cè)試的
是I/O密集型任務(wù),事實(shí)上大部分的任務(wù)都是I/O密集型的,即大部分任務(wù)消耗集中在的輸入輸出。而CPU密集型任務(wù)主
要消耗CPU資源進(jìn)行計(jì)算,當(dāng)任務(wù)為CPU密集型時(shí),核心池線程數(shù)設(shè)置為CPU核數(shù)+1即可)
package com.lc.concurrent;import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadPoolExecutor;public class CreateThreads {public synchronized static void main(String[] args) {System.out.println(MyThreadPoolExecutor.PROCESSORS);new CreateThreads().test();}public synchronized void test(){ThreadPoolExecutor threadPoolExecutor=new MyThreadPoolExecutor().createThreadPool();for (int i = 0; i <= 100; i++) {MyTask myTask = new MyTask(i);threadPoolExecutor.execute(myTask);}threadPoolExecutor.shutdown();}}class MyTask implements Runnable{private int i;public MyTask(int i){this.i=i;}@Overridepublic void run() {System.out.println("任務(wù)"+i+"開(kāi)始執(zhí)行"+System.currentTimeMillis());for (int i=0;i<32766;i++){Random random=new Random();int randNum=random.nextInt();int[] a={1,2,3,4,5,6,9,18,290,238,991,100,19,1932,randNum};Arrays.sort(a);Arrays.hashCode(a);Arrays.stream(a);}System.out.println("任務(wù)"+i+"結(jié)束執(zhí)行"+System.currentTimeMillis());} }
本機(jī)CPU核數(shù)為4,可同時(shí)處理8線程,測(cè)試結(jié)果如下:
核心池線程數(shù)量 執(zhí)行耗時(shí)(毫秒,多次測(cè)試結(jié)果以/間隔)4 474/479/4718 430/436/42112 432/425/43816 437/431/44920 471/481/469 可以發(fā)現(xiàn)當(dāng)線程數(shù)量小于CPU核數(shù)兩倍時(shí)速度明顯較慢,超過(guò)兩倍后速度差不多,當(dāng)核心池?cái)?shù)量過(guò)多時(shí),速度又會(huì)顯著下降
由此可以看出,核心池線程數(shù)量大小應(yīng)在CPU核數(shù)兩倍以上且不宜過(guò)多。
所以說(shuō),將線程池的核心池線程數(shù)量配置為CPU核數(shù)的兩倍是比較合適的。
轉(zhuǎn)載于:https://www.cnblogs.com/coder-lichao/p/10931919.html
總結(jié)
以上是生活随笔為你收集整理的根据CPU核数合理设置线程池大小的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 鼋头渚免费政策
- 下一篇: POJ1149-PIGS