http://blog.sina.com.cn/s/blog_7d1968e20102x1x4.html
线程池的创建
private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 100,
30, TimeUnit.SECONDS, new LinkedBlockingDeque<>(50), new ThreadPoolExecutor.CallerRunsPolicy());
线程销毁
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
@Service
public class SendMqThreadPool {
private static ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
static {
threadPoolExecutor.setCorePoolSize(20);
threadPoolExecutor.setMaxPoolSize(100);
threadPoolExecutor.setQueueCapacity(50);
threadPoolExecutor.setKeepAliveSeconds(20);
threadPoolExecutor.setWaitForTasksToCompleteOnShutdown(true);
threadPoolExecutor.setAwaitTerminationSeconds(5);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolExecutor.initialize();
}
public void execute(Runnable runnable) {
threadPoolExecutor.execute(runnable);
}
}
还可以使用JVM钩子优雅关闭线程池。Runtime.getRuntime.addShutdownHook(Xxxxx);