/**
* 线程管理
*
* @author melon.wang
*/
public class ThreadManager {
/**
* 核心线程数
*/
private static final int CORE_POLL_SIZE = getDefaultThreadPoolSize();
/**
* 最大线程数
*/
private static final int MAX_POOL_SIZE = CORE_POLL_SIZE * 50;
/**
* 非核心线程最长存活时间
*/
private static final int KEEP_ALIVE_TIME_IN_SECONDS = 30;
private static ThreadFactory threadFactory = new ThreadFactory() {
private AtomicInteger count = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("Melon-Pool-".concat(String.valueOf(count.getAndIncrement())));
return thread;
}
};
private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POLL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME_IN_SECONDS, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
private ThreadManager() {
}
/**
* 执行线程任务
*/
public static void execute(Runnable runnable) {
threadPoolExecutor.execute(runnable);
}
/**
* 取消线程任务
*/
public static void cancel(Runnable runnable) {
if (threadPoolExecutor != null && !threadPoolExecutor.isShutdown() && !threadPoolExecutor.isTerminated()) {
// 移除
threadPoolExecutor.remove(runnable);
}
}
/**
* 取消所有线程任务
*/
public static void close() {
if (threadPoolExecutor != null && !threadPoolExecutor.isShutdown()) {
// 移除
threadPoolExecutor.shutdown();
}
}
/**
* 默认线程池线程个数
*/
private static int getDefaultThreadPoolSize() {
return Runtime.getRuntime().availableProcessors();
}
}