1

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;

public class ExecutorUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorUtils.class);

private static volatile ThreadPoolExecutor threadPool = null;

private ExecutorUtils() {

}

public static void submit(Runnable runnable) {
getThreadPool().execute(runnable);
}

public static ThreadPoolExecutor getThreadPool() {
try {
if (threadPool == null) {
Class<ExecutorUtils> var0 = ExecutorUtils.class;
synchronized (ExecutorUtils.class) {
if (threadPool == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();
int threadNum = cpuNum * 2;
threadPool = new ThreadPoolExecutor(threadNum, threadNum + 1, 2147833647L, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>(Integer.MAX_VALUE), Executors.defaultThreadFactory(), new AbortPolicy() {
public void rejectedException(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
});
}
}
}
} catch (Exception e) {
LOGGER.error("创建线程池异常!===>{}", e);
}
return threadPool;
}
}

 

2

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTaskUtils {
private static int CAPACITY = 10000;

// 线程池核心线程数
public static int CORE_POOL_SIZE = 10;

// 线程池最大线程数
private static int MAXIMUM_POOL_SIZE = 30;

// 额外线程空状态生存时间
private static Long KEEP_ALIVE_TIME = 0L;

private static TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;

private static ExecutorService threadPool;

static {

BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<Runnable>(CAPACITY);

RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();

threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT, workingQueue,
rejectedExecutionHandler);
}

/**
* 提交任务
*
* @param runnable
* @throws CommonException
*/
public static void submit(Runnable runnable) {
threadPool.execute(runnable);
}


}

 

测试方法

 

public class ThreadPools {


private static void testss() {
ExecutorUtils.submit(() -> {
System.out.println(7);
});
for (int i = 0; i < 999; i++) {
ThreadPoolTaskUtils.submit(() -> {
System.out.println(7);
});
}
}

public static void main(String[] args) {
testss();
}

 

posted on 2022-02-10 22:45  xue123  阅读(577)  评论(0编辑  收藏  举报