package com.example.threadpool.service;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
- @program: demo-threadpool
- @description
- @author: tina.liu
- @create: 2022-04-03 20:40
**/
@Slf4j
public class ThreadPoolUtil {
public static final ThreadPoolUtil EXCUTOR = new ThreadPoolUtil();
//核心線程池的數(shù)量僚焦,同時(shí)能夠執(zhí)行的線程數(shù)量
private int corePoolSize;
//最大線程池?cái)?shù)量勤婚,表示當(dāng)緩沖隊(duì)列滿的時(shí)候能繼續(xù)容納的等待任務(wù)的數(shù)量
private int maxPoolSize;
//存活時(shí)間
private long keepAliveTime = 1;
private TimeUnit unit = TimeUnit.HOURS;
private ThreadPoolExecutor executor;
private ThreadPoolUtil() {
//給corePoolSize賦值:當(dāng)前設(shè)備可用處理器核心數(shù)*2 + 1,能夠讓cpu的效率得到最大程度執(zhí)行(有研究論證的)
corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
maxPoolSize = corePoolSize;
executor = new ThreadPoolExecutor(
//當(dāng)某個(gè)核心任務(wù)執(zhí)行完畢筐钟,會(huì)依次從緩沖隊(duì)列中取出等待任務(wù)
corePoolSize,
// 然后new LinkedBlockingQueue<Runnable>(),然后maximumPoolSize,但是它的數(shù)量是包含了corePoolSize的
maxPoolSize,
//表示的是maximumPoolSize當(dāng)中等待任務(wù)的存活時(shí)間
keepAliveTime,
unit,
//緩沖隊(duì)列颁井,用于存放等待任務(wù)旅薄,Linked的先進(jìn)先出
new LinkedBlockingQueue<Runnable>(),
new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
new ThreadPoolExecutor.AbortPolicy()
);
log.info("Class ThreadPoolUtil field corePoolSize ={},maxPoolSize ={} ", corePoolSize, maxPoolSize);
}
/**
* 執(zhí)行任務(wù) 無返回值
*
* @param runnable
*/
public void execute(Runnable runnable) {
if (runnable != null) {
executor.execute(runnable);
}
}
/**
* 執(zhí)行任務(wù) 有返回值
*
* @param callable
*/
public <T> T executeReturn(Callable<T> callable) {
try {
return executor.submit(callable).get();
} catch (Exception e) {
log.error("Class ThreadPoolUtil executeReturn fail message :{}",e.getMessage());
}
return null;
}
/**
* 執(zhí)行任務(wù) 有返回值
*
* @param callables
*/
public <T> List<Future<T>> executeReturn(List<Callable<T>> callables) {
try {
return executor.invokeAll(callables);
} catch (Exception e) {
log.error("Class ThreadPoolUtil executeReturn fail message :{}",e.getMessage());
}
return null;
}
/**
* 移除任務(wù)
*
* @param runnable
*/
public void remove(Runnable runnable) {
if (runnable != null) {
executor.remove(runnable);
}
}
private static class DefaultThreadFactory implements ThreadFactory {
//線程池的計(jì)數(shù)
private static final AtomicInteger poolNumber = new AtomicInteger(1);
//線程的計(jì)數(shù)
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final String namePrefix;
private final int threadPriority;
DefaultThreadFactory(int threadPriority, String threadNamePrefix) {
this.threadPriority = threadPriority;
this.group = Thread.currentThread().getThreadGroup();
this.namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-";
}
@Override
public Thread newThread(@NonNull Runnable r) {
Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
// 返回True該線程就是守護(hù)線程
// 守護(hù)線程應(yīng)該永遠(yuǎn)不去訪問固有資源,如:數(shù)據(jù)庫憔四、文件等背亥。因?yàn)樗鼤?huì)在任何時(shí)候甚至在一個(gè)操作的中間發(fā)生中斷。
if (thread.isDaemon()) {
thread.setDaemon(false);
}
thread.setPriority(threadPriority);
return thread;
}
}
}