面试必问(1):线程池详解
/**
* WangGaozhuo
* q-35704404
* 20210113
*/
public class ThreadUtil {
public static ThreadPoolExecutor GLOBAL_THREAD_POOL;
static {
final int cores = Runtime.getRuntime().availableProcessors();
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000);
ThreadFactory treadFactory = new NameTreadFactory();
/**
* defaultThreadFactory创建的线程有相同优先级,非守护线程,有线程名称
*/
//treadFactory = Executors.defaultThreadFactory();
/**
* privilegedThreadFactory:
* extends DefaultThreadFactory,
* 可以让运行在这个线程中的任务拥有和这个线程相同的访问控制和classLoader
*/
//treadFactory = Executors.privilegedThreadFactory();
int corePoolSize = cores * 2 + 2;
int maximumPoolSize = corePoolSize + 2;
int keepAliveTime = 60;
GLOBAL_THREAD_POOL = new ThreadPoolExecutor(
//核心线程数
corePoolSize,
//最大线程数
maximumPoolSize,
//允许的空闲时间,默认情况下非核心线程的空闲时间
keepAliveTime,
//keepAliveTime时间单位
TimeUnit.SECONDS,
workQueue,
treadFactory,
/**
* 当前线程池满了,并且workQueue也满了,需要采取的策略处理任务
* new ThreadPoolExecutor.AbortPolicy() //抛异常
* new ThreadPoolExecutor.CallerRunsPolicy() //用调用者所在的线程执行任务
* new ThreadPoolExecutor.DiscardOldestPolicy() //丢弃队列中最前的任务并执行当前的任务
* new ThreadPoolExecutor.DiscardPolicy() // 丢弃当前任务
*/
new ThreadPoolExecutor.DiscardOldestPolicy());
/**
* 核心线程也会被回收
*/
//GLOBAL_THREAD_POOL.allowCoreThreadTimeOut(true);
}
static class NameTreadFactory implements ThreadFactory {
private final AtomicInteger mThreadNum = new AtomicInteger(1);
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "thread-" + mThreadNum.getAndIncrement());
return t;
}
}
public static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void printThreadName(String tag) {
System.out.println(tag + ".Thread Name : " + Thread.currentThread().getName());
}
public static void main(String[] args) {
/**
* 提交任务交给线程池执行
* GLOBAL_THREAD_POOL.execute()
* 提交任务能返回结果
* GLOBAL_THREAD_POOL.submit()
*/
Future<String> result = GLOBAL_THREAD_POOL.submit(() -> "拿到执行结果");
String resStr = null;
try {
/**
* 拿到线程池中线程执行的结果
*/
resStr = result.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(resStr);
//返回线程池执行和未执行的总数
//GLOBAL_THREAD_POOL.getTaskCount();
//已经完成任务数量
//GLOBAL_THREAD_POOL.getCompletedTaskCount();
//线程池当前线程数量
//GLOBAL_THREAD_POOL.getPoolSize();
//线程池中正在执行的任务数量
//GLOBAL_THREAD_POOL.getActiveCount();
//等待任务执行完,关闭线程池
GLOBAL_THREAD_POOL.shutdown();
//立即关闭线程池,不等任务执行完
//GLOBAL_THREAD_POOL.shutdownNow();
}
}