線程池最佳線程數(shù)量到底要如何配置?
一、前言
?
二、從實戰(zhàn)開始
public class MyCallable implements Callable<String> {public String call() throws Exception {System.out.println("MyCallable call");return "success";}public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();try {Futurefuture = threadPool.submit(new MyCallable()); System.out.println(future.get());} catch (Exception e) {System.out.println(e);} finally {threadPool.shutdown();}}}
三、創(chuàng)建線程池的方法







public class MyWorker implements Runnable {public void run() {System.out.println("MyWorker run");}public static void main(String[] args) {ExecutorService threadPool = Executors.newFixedThreadPool(8);try {threadPool.execute(new MyWorker());} catch (Exception e) {System.out.println(e);} finally {threadPool.shutdown();}}}
public class MyTask implements Runnable {public void run() {System.out.println("MyTask call");}public static void main(String[] args) {ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(8);try {scheduledExecutorService.schedule(new MyRunnable(), 60, TimeUnit.SECONDS);} finally {scheduledExecutorService.shutdown();}}}
?
四、自定義線程池


corePoolSize:核心線程數(shù)maximumPoolSize:最大線程數(shù)keepAliveTime:空閑線程回收時間間隔unit:空閑線程回收時間間隔單位workQueue:提交任務的隊列,當線程數(shù)量超過核心線程數(shù)時,可以將任務提交到任務隊列中。比較常用的有:ArrayBlockingQueue; LinkedBlockingQueue; SynchronousQueue;threadFactory:線程工廠,可以自定義線程的一些屬性,比如:名稱或者守護線程等handler:表示當拒絕處理任務時的策略
ThreadPoolExecutor.AbortPolicy:丟棄任務并拋出RejectedExecutionException異常。ThreadPoolExecutor.DiscardPolicy:也是丟棄任務,但是不拋出異常。ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務,然后重新嘗試執(zhí)行任務(重復此過程)ThreadPoolExecutor.CallerRunsPolicy:由調用線程處理該任務
public class MyThreadPool implements Runnable {private static final ExecutorService executorService = new ThreadPoolExecutor(8,10,30,TimeUnit.SECONDS,new ArrayBlockingQueue<>(500),new ThreadPoolExecutor.AbortPolicy());public void run() {System.out.println("MyThreadPool run");}public static void main(String[] args) {int availableProcessors = Runtime.getRuntime().availableProcessors();try {executorService.execute(new MyThreadPool());} catch (Exception e) {System.out.println(e);} finally {executorService.shutdown();}}}
五、最佳線程數(shù)
什么是IO密集型? 比如:頻繁讀取磁盤上的數(shù)據(jù),或者需要通過網(wǎng)絡遠程調用接口。 什么是CPU密集型? 比如:非常復雜的調用,循環(huán)次數(shù)很多,或者遞歸調用層次很深等。
int availableProcessors = Runtime.getRuntime().availableProcessors();最佳線程數(shù)目 = ((線程等待時間+線程CPU時間)/線程CPU時間 )* CPU數(shù)目有道無術,術可成;有術無道,止于術
歡迎大家關注Java之道公眾號
好文章,我在看??
評論
圖片
表情
