今天小G,在開發一個項目的時候,導入excel,20萬數據到數據庫,該數據爲業務數據
,無法讓DBA進行導入,然後小G就想,那就線程走起;
說起線程就想起線程池,大家也知道,線程池可以防止
1、創建同類的線程導致消耗完內存
2、創建線程和銷燬過度切換問題
那目前四種線程(小G也是網上查詢下資料,因爲也好久不用)
線程 | 優點 |
---|---|
newCachedThreadPool | 無需考慮線程長度,空閒可以回收,無空閒新增,新增無極限 |
newFixedThreadPool | 需要賦值線程數量,可以控制併發數,超過可以在隊列 |
newScheduledThreadPool | 可以延遲執行線程,應該是任務用這個執行 |
newSingleThreadExecutor | 看名就是單例,有順序的執行制定的FIFO,LIFO |
根據需求使用的是newFixedThreadPool,爲什麼這樣考慮,這個線程週期可能比較長,最喜歡裏面的QUEUE隊列,設置完線程數,超過的可以在隊列過程中等待,小G感覺如果使用newCachedThreadPool ,無法控制線程數量,應該是週期比較小(線程執行時間段),併發量不大,才使用,因爲他會無限制開線程
1、ThreadPoolExecutor
public class ThreadUtil{
/**
* 線程數
*/
private static final int CORE_SIZE = 10;
/**
最大值
*/
private static final int MAX_SIZE = 20;
/**
* 線程空閒多久進行回收
*/
private static final long KEEP_ALIVE_TIME = 60;
/**
* 阻塞隊列的大小
*
*/
private static final int QUEUE_SIZE = 2000;
/**
* 使用多少的隊列
*/
private static int USER_QUEUE_SIZE=0;
/**
* 使用多少的隊列
* @return
*/
public static int getUserQueueSize() {
return USER_QUEUE_SIZE;
}
private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());
public static ThreadPoolExecutor getThreadPool() {
if(threadPool==null){
new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());
}
USER_QUEUE_SIZE = threadPool.getQueue().size();
return threadPool;
}
}
2、Thread代碼
ThreadPoolExecutorUtil.getThreadPool().excel(new Thread1 ());
3、裏面new runnabel寫個類就可以
public class Thread1 implements Runnable, Serializable{
@Override
public void run() {
}
}
小結:如果大家趕緊,怕業務上去無法控制,可以多設置下QUEUE的隊列數,然後在使用過程中,自己自定義一個值,先跟自己設計的值比較,這樣後續如果量比較大也好控制,後續我會把如何處理大量數據通過excel導入數據可以,通過線程哈,寫的不好小G讓大家見笑
後續:爲什麼建議大家實驗ThreaPoolExecutor 而不適用executors方法:
- FixedThreadPool 和 SingleThreadExecutor : 允許請求的隊列長度爲
Integer.MAX_VALUE,可能堆積大量的請求,從而導致 OOM。 - CachedThreadPool 和 ScheduledThreadPool : 允許創建的線程數量爲
Integer.MAX_VALUE ,可能會創建大量線程,從而導致 OOM。
另外,大家可以使用cpu來決定線程數
下面爲獲取cpu的數量
/**
* 根據cpu的數量動態的配置核心線程數和最大線程數
*/
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
其中 ,其中可以有優化:最大優化爲CPU_COUNT * 2 + 1,最多優化爲 CPU_COUNT * 2 + 1;(隊列滿的時候開啓該配置線程數量)