Future.get抛出TimeoutException,并不会中断或者取消任务

static ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * get 出现TimeoutException,并不会中断或者取消运算线程
     * @throws InterruptedException
     */
    @Test
    void testGetTimeoutException() throws InterruptedException {
        final Future<Long> future = executorService.submit(() -> {
            delay(3000);
            System.out.println("delay 3000");
            return 888L;
        });

        try {
            final long value = future.get(1, TimeUnit.SECONDS);
            System.out.println("value = " + value);
            Assertions.fail();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            // get timeout
            System.out.println("get timeout");
        }

        executorService.shutdown();
        executorService.awaitTermination(100, TimeUnit.SECONDS);

        System.out.println("wait shutdown");
    }
// 输出
get timeout
delay 5000
wait shutdown

 


版权声明:本文为weixin_40677588原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。