主要采用guava和原生java并发包。
package com.ky.common;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.concurrent.*;
/**
线程池工具类
-
@author Administrator
*/
public class ThreadPoolUtil {private static final Log logger = LogFactory.getLog(ThreadPoolUtil.class);
private static ThreadPoolUtil threadPool;
private ThreadPoolExecutor executor;private TimeUnit unit = TimeUnit.SECONDS;
public ThreadPoolUtil() {
LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1024);
int corePoolSize = 10;
long keepAliveTime = 1;
int maximumPoolSize = 15;
final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("hbase-thread-%d").build();
executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new ThreadPoolExecutor.AbortPolicy());
System.out.println("线程池初始化成功");
}public static ThreadPoolUtil init() {
if (threadPool == null) {
threadPool = new ThreadPoolUtil();
}
return threadPool;
}public void awaitTermination() throws InterruptedException {
logger.info("Thread pool ,awaitTermination started, please wait till all the jobs complete.");
long timeout = 10;
executor.awaitTermination(timeout, unit);
}public void execute(Runnable t) {
executor.execute(t);
}public void execute(Thread t) {
executor.execute(t);
}public int getQueueSize() {
return executor.getQueue().size();
}public void shutdown() {
getExecutor().shutdown();
}private ThreadPoolExecutor getExecutor() {
return executor;
}public Future<?> submit(Runnable t) {
return executor.submit(t);
}@SuppressWarnings({"unchecked", "rawtypes"})
public Future<?> submit(Callable t) {
return getExecutor().submit(t);
}
}