@Slf4j
@Component
public class ThreadExecutor {
private ThreadFactory factory = new NamedThreadFactory("mall-thread-", false);
/**
* 最大线程数
*/
private static final int MAX_CONCURRENT = Runtime.getRuntime().availableProcessors() * 2;
private ExecutorService execute;
/**
* 执行队列
*/
private static BlockingQueue<Runnable> executeQueue = new ArrayBlockingQueue<>(50);
{
execute = new ThreadPoolExecutor(MAX_CONCURRENT, MAX_CONCURRENT * 2, 30L, TimeUnit.SECONDS, executeQueue, factory, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.error("拒绝任务-");
}
});
//增加关闭钩子
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
log.info("执行线程池关闭钩子---------");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("执行线程池关闭钩子---------2秒后");
execute.shutdown();
while (!executeQueue.isEmpty()) {
log.info("队列暂不为空,剩余:{}", executeQueue.size());
}
try {
if (!execute.awaitTermination(1, TimeUnit.SECONDS)) {
execute.shutdownNow();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
}
public boolean executeJob(Runnable job) {
try {
execute.execute(job);
} catch (Exception exception) {
return false;
}
return true;
}
public <T> Future<T> submit(Callable<T> job) {
try {
return execute.submit(job);
} catch (RejectedExecutionException e) {
log.error("Task executing was rejected.", e);
throw new UnsupportedOperationException("Unable to submit the task, rejected.", e);
}
}
}