1. 程式人生 > >JAVA並發編程>>線程池的實現

JAVA並發編程>>線程池的實現

keepalive sys seconds pre str imu xxx block style

線程創建傾向

如果運行的線程的小於corePoolSize,當請求來時,創建新線程。

如果運行corePoolSize或多於,當請求來時,排隊。

如果請求不能進行排隊,且小於maximumPoolSize創建新線程,請求會被拒絕。

不要使用Executors.newXXXThreadPool()快捷方法創建線程池,因為這種方式會使用無界的任務隊列,為避免OOM。

1、創建線程池

 1 package com.learn.threadTest;
 2 
 3 
 4 import java.util.concurrent.ArrayBlockingQueue;
 5 import
java.util.concurrent.ExecutorService; 6 import java.util.concurrent.TimeUnit; 7 import java.util.concurrent.ThreadPoolExecutor; 8 9 public class DefineThreadPoolFactory { 10 11 12 private final static int corePoolSize = 5;//活躍線程數 13 private final static int maximumPoolSize = 20;//
最大線程數 14 private final static long keepAliveTime = 0;//臨時線程活躍時長 15 16 public static ExecutorService threadPoolFactory () { 17 ExecutorService executorService = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit.SECONDS,new ArrayBlockingQueue<>(128));
18 return executorService; 19 } 20 public static void main(String[] arg0) { 21 threadPoolFactory().submit(new Runnable() { 22 @Override 23 public void run() { 24 Thread.currentThread().setName("蝦來了"); 25 System.out.println("獲取到線程資源,線程名{"+Thread.currentThread().getName()+"}"); 26 System.out.println("獲取到線程資源,線程名{"+Thread.currentThread().getId()+"}"); 27 } 28 }); 29 } 30 }

執行結果

技術分享圖片

創建線程是昂貴的開銷,請合理創建線程。另外,所有線程,請設定一個有意義的名字,方便問題排查。

JAVA並發編程>>線程池的實現