public class ThreadPoolKits extends Object
1. 优雅关闭线程池的(via guava)
2. 创建可自定义线程名的ThreadFactory(via guava)
3. 防止第三方Runnable未捕捉异常导致线程跑飞
copy from vipshop VJTools(com.vip.vjtools.vjkit.concurrent.threadpool.ThreadPoolUtil) and made some changes.
| 构造器和说明 |
|---|
ThreadPoolKits() |
| 限定符和类型 | 方法和说明 |
|---|---|
static ThreadFactory |
buildThreadFactory(String threadNamePrefix)
创建ThreadFactory,使得创建的线程有自己的名字而不是默认的"pool-x-thread-y"
使用了Guava的工具类
|
static ThreadFactory |
buildThreadFactory(String threadNamePrefix,
boolean daemon)
可设定是否daemon, daemon线程在主线程已执行完毕时, 不会阻塞应用不退出, 而非daemon线程则会阻塞.
|
static boolean |
gracefulShutdown(ExecutorService threadPool,
int shutdownTimeoutMills)
按照ExecutorService JavaDoc示例代码编写的Graceful Shutdown方法.
|
static boolean |
gracefulShutdown(ExecutorService threadPool,
int shutdownTimeout,
TimeUnit timeUnit) |
static Runnable |
safeRunnable(Runnable runnable)
防止用户没有捕捉异常导致中断了线程池中的线程, 使得SchedulerService无法继续执行.
|
public static boolean gracefulShutdown(ExecutorService threadPool, int shutdownTimeoutMills)
先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
如果1/2超时时间后, 则调用shutdownNow,取消在workQueue中Pending的任务,并中断所有阻塞函数.
如果1/2超时仍然超時,則強制退出.
另对在shutdown时线程本身被调用中断做了处理.
返回线程最后是否被中断.
使用了Guava的工具类
MoreExecutors.shutdownAndAwaitTermination(ExecutorService, long, TimeUnit)public static boolean gracefulShutdown(ExecutorService threadPool, int shutdownTimeout, TimeUnit timeUnit)
public static ThreadFactory buildThreadFactory(String threadNamePrefix)
使用了Guava的工具类
ThreadFactoryBuilder.build()public static ThreadFactory buildThreadFactory(String threadNamePrefix, boolean daemon)
Copyright © 2019. All rights reserved.