1、executorService.shutdown()关闭线程
1.1、线程任务
class TaskShutDownPool implements Runnable{
@Override
public void run() {
try {
Thread.sleep(5000);
log.info("TaskShutDownPool:{}",Thread.currentThread().getName());
} catch (InterruptedException e) {
log.error("TaskShutDownPool.interrupted:{}",e.getMessage(),e);
}
}
}
1.2、测试用例
@Test
public void testShutDown() throws InterruptedException {
//创建线程实例
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
//执行线程任务
executorService.execute(new TaskShutDownPool());
}
Thread.sleep(1000);
log.info("testShutDown.status:{},before",executorService.isShutdown());
//关闭线程
executorService.shutdown();
log.info("testShutDown.status:{},before",executorService.isShutdown());
Thread.sleep(500);
log.info("testShutDown.shutDown");
executorService.execute(new TaskShutDownPool());
}
1.3、日志
调用executorService.shutdown()关闭线程之前,我们线程正常执行,
调用之后,线程此时是关闭的,但是已提交的线程不会立即关闭
这里表示,没有执行完的线程可以继续执行,但是行提交的线程则不允许提交。
2、executorService.isTerminated()关闭线程
2.1、测试用例
//创建线程实例
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
//执行线程任务
executorService.execute(new TaskShutDownPool());
}
Thread.sleep(1000);
log.info("testShutDown.status:{},before",executorService.isTerminated());
//关闭线程
executorService.isTerminated();
log.info("testShutDown.status:{},after",executorService.isTerminated());
Thread.sleep(500);
log.info("testShutDown.isTerminated");
executorService.execute(new TaskShutDownPool());
2.2、日志
日志false表示线程没有完全结束。
3、executorService.shutdownNow()线程关闭
立即关闭安线程
4、优雅关闭线程案例
@Slf4j
public class ThreadPoolUtils {
private ThreadPoolUtils(){}
public static void shutDownPool(ExecutorService pool, int shutDownTimeout
, int shutDownNowTimeout, TimeUnit timeUnit){
pool.shutdown();
try {
if (!pool.awaitTermination(shutDownTimeout,timeUnit)){
pool.shutdownNow();
if (pool.awaitTermination(shutDownNowTimeout,timeUnit)){
log.error("ThreadPoolUtils.shutDownPool.error");
}
}
} catch (InterruptedException e) {
log.error("ThreadPoolUtils.shutDownPool.interrupt.error:{}",e.getMessage(),e);
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
感谢小伙伴观看!可以把你的意见留在评论区。