package com.yitong.mobile.common.base.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 線程池管理 管理整個(gè)項(xiàng)目中所有的線程,所以不能有多個(gè)實(shí)例對(duì)象
*/
public class ThreadPoolManager {
private static ThreadPoolManager mInstance = new ThreadPoolManager();
public static ThreadPoolManager getInstance() {
return mInstance;
}
private int corePoolSize;//核心線程池的數(shù)量,同時(shí)能夠執(zhí)行的線程數(shù)量
private int maximumPoolSize;//最大線程池?cái)?shù)量,表示當(dāng)緩沖隊(duì)列滿的時(shí)候能繼續(xù)容納的等待任務(wù)的數(shù)量
private long keepAliveTime = 1;//存活時(shí)間
private TimeUnit unit = TimeUnit.HOURS;
private ThreadPoolExecutor executor;
private ThreadPoolManager() {
/**
* 給corePoolSize賦值:當(dāng)前設(shè)備可用處理器核心數(shù)*2 + 1,能夠讓cpu的效率得到最大程度執(zhí)行(有研究論證的)
*/
corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
maximumPoolSize = corePoolSize; //雖然maximumPoolSize用不到,但是需要賦值,否則報(bào)錯(cuò)
executor = new ThreadPoolExecutor(
corePoolSize, //當(dāng)某個(gè)核心任務(wù)執(zhí)行完畢,會(huì)依次從緩沖隊(duì)列中取出等待任務(wù)
maximumPoolSize, //5,先corePoolSize,然后new LinkedBlockingQueue<Runnable>(),然后maximumPoolSize,但是它的數(shù)量是包含了corePoolSize的
keepAliveTime, //表示的是maximumPoolSize當(dāng)中等待任務(wù)的存活時(shí)間
unit,
new LinkedBlockingQueue<Runnable>(), //緩沖隊(duì)列,用于存放等待任務(wù),Linked的先進(jìn)先出
Executors.defaultThreadFactory(), //創(chuàng)建線程的工廠
new ThreadPoolExecutor.AbortPolicy() //用來(lái)對(duì)超出maximumPoolSize的任務(wù)的處理策略
);
}
/**
* 執(zhí)行任務(wù)
*/
public void execute(Runnable runnable) {
if (runnable == null) {
return;
}
executor.execute(runnable);
}
/**
* 從線程池中移除任務(wù)
*/
public void remove(Runnable runnable) {
if (runnable == null) {
return;
}
executor.remove(runnable);
}
}
線程池封裝
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。