线程池创建

package net.icarefx.booking.util.threadpool;

 

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* Create by wfs on 2020/06/01
* 线程工具类
*/
public class ThreadPoolUtils {
//使用volatile关键字保其可见性
volatile private static ThreadPoolExecutor threadPool = null;

/**
* 无返回值直接执行
*
* @param runnable
*/
public static void execute(Runnable runnable) {
getThreadPool().execute(runnable);
}

/**
* 返回值直接执行
*
* @param callable
*/
public static <T> Future<T> submit(Callable<T> callable) {
return getThreadPool().submit(callable);
}

private static ThreadPoolExecutor getThreadPool() {//单例加锁创建线程池
try {
if (threadPool != null) {
return threadPool;
} else {
synchronized (ThreadPoolUtils.class) {
if (threadPool == null) {
Thread.sleep(300);
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
System.out.println(cpuNum);
int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
threadPool = new ThreadPoolExecutor(
threadNum - 1,// 核心线程数
threadNum, // 最大线程数
5000, // 空闲线程存活时间
TimeUnit.MILLISECONDS,// 单位毫秒
new ArrayBlockingQueue<Runnable>(10),// 采用有界队列防止oom
Executors.defaultThreadFactory(),// 创建工厂
new ThreadPoolExecutor.AbortPolicy() {// 队列满了,当前线程数大于最大线程数的拒绝策略(抛异常)
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
}
);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return threadPool;
}






public static void main(String[] args){

//ExecutorService threadPool=Executors.newFixedThreadPool(5);


for (int i = 0; i < 10; i++)
{
ThreadPoolUtils.execute(new Runnable(){

@Override
public void run()
{//这里写逻辑
System.out.println(Thread.currentThread().getName()+"在运行");
// TODO Auto-generated method stub
}
});
}
}
}

上一篇:线程池源码分析-ThreadPoolExecutor


下一篇:线程