关闭时可以使用以下代码java
public static void waitUntilTerminate(final ExecutorService executorService, final int timeout) { try { executorService.shutdown(); if (!executorService.awaitTermination(timeout, TimeUnit.SECONDS)) { //超时后直接关闭 executorService.shutdownNow(); } } catch (InterruptedException e) { //awaitTermination 出现中断异常也将触发关闭 executorService.shutdownNow(); } }
可是实际使用中,可能会出现即便使用了shutdownNow
方法,仍是没法终止线程的问题,那是由于你的线程没法被中断测试
shutdownNow
方法简单理解就是给在运行的线程发一个中断信号,若是你的线程忽略这个信号,那就没法停下来this
举个例子来讲明这个问题线程
public class ShutDownUtilsTest { private ExecutorService executorService; @Before public void init() { executorService = Executors.newFixedThreadPool(1); } @Test public void shutDownOKTest() { ShutDownUtils.waitUntilTerminate(executorService, 1); CommonUtils.sleep(1); //等待线程处理中断 Assert.assertTrue(executorService.isTerminated()); } @Test public void shutDownNowFailTest() { executorService.execute(this::canNotStopThread); ShutDownUtils.waitUntilTerminate(executorService, 0); CommonUtils.sleep(1); //等待线程处理中断 Assert.assertFalse(executorService.isTerminated()); } @Test public void shutDownNowOKTest() { executorService.execute(this::stopThread); ShutDownUtils.waitUntilTerminate(executorService, 0); CommonUtils.sleep(1); //等待线程处理中断 Assert.assertTrue(executorService.isTerminated()); } private void canNotStopThread() { for (long i = 0; i < Long.MAX_VALUE; i++) { } } private void stopThread() { for (long i = 0; i < Long.MAX_VALUE && !Thread.currentThread().isInterrupted(); i++) { } } }
从上面的测试用例能够看到canNotStopThread
没法被shutDownNow
终止code
然而stopThread
能够被正常终止,由于经过Thread.currentThread().isInterrupted()
在判断线程是否收到了中断信号it