JAVA篇 八月 23, 2019

Java 开启子线程执行其他操作,并获取结果

文章字数 475 阅读约需 1 mins. 阅读次数

示例代码,10后抛出超时错误,并且取消子线程任务的执行

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<String> future = executorService.submit(() -> {
                ....
            }
    );

    try {
        return future.get(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(true);
        executorService.shutdown();
        return new ArrayList<>();
    }
0%