【问题标题】:How to return a result at the moment of an interrupt in Java Future如何在 Java Future 中断时返回结果
【发布时间】:2021-02-03 16:46:00
【问题描述】:

我有一个我使用执行服务提交的任务列表。我正在使用线程的时间限制执行并在未来对象中等待结果。但是现在我想在可调用线程被中断时收集结果。我有一个结果,但我无法执行 future.get() 因为它已经由于超时而被取消。如何将部分结果存储在 future 对象中?

【问题讨论】:

    标签: java concurrency future


    【解决方案1】:

    当限时线程被中断时,你应该会得到一个异常。

    Future<String> future = executorService.submit(callableTask);
    String result = null;
    try {
        result = future.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    

    【讨论】:

    • 是的。同意,但是当future.get()中发生异常时我应该如何获取结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多