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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章