java - 如何中断 Future,但仍然等待它完成?

标签 java multithreading interrupt future

我有一系列使用 ExecutorService 排队的作业。如果用户点击“取消”,那么我需要通知那些工作他们应该尽快停止。但是,有时它们位于代码的关键部分,必须在父线程继续执行之前完成。我怎样才能做到这一点?我不想使用我自己的取消标志,因为那不会导致 sleep /等待退出。

我认为这段代码可以工作,但它不符合我的要求:

while( true ) {
    //Do this in a loop. If our thread is interrupted, we call cancel on the threads (to try to get them to hurry up by skipping non-essential stuff), but we still need to wait for them to finish.
    try {
        for( Future<Void> future : futures ) {
            future.get(); //I thought that this would continue waiting, even if I call cancel, but it doesn't. How can I wait for the future to finish?
        }
        break; //OK, everything is finished, exit the wait loop.
    } catch( InterruptedException e ) {
        wasInterrupted = true; //We'll rethrow the exception laster as an AbortException.
        //Need to wait for futures to finish, even if it's canceled.
        log.info( "Attempting to interrupt threads that are reading changes..." );
        for( Future<Void> future : futures ) {
            future.cancel( true ); //I want to tell the threads to 'hurry up' and skip non-essential stuff.
        }
    } catch( ExecutionException e ) {
        throw e.getCause();
    }
}

//I shouldn't get to this line until all futures have finished!

最佳答案

How to interrupt a Future, but still wait for it to finish?

有趣的问题。您的代码将无法正常工作,因为当您取消 Future 时,正如您所发现的,您无法再次对其调用 get(),因为那样会抛出 CancellationException

如果我理解您的要求:

  • 您需要能够中断线程,因为您想要停止 sleep 等待等。
  • 您仍然希望能够在任务取消后获得任务的结果。

唯一要做的就是在这里使用Future。而是使用您自己的作业包装器并等待 ExecutorService 本身以 executorService.awaitTermination(...) 完成。

如果您需要任务的结果,那么您的 Runnable 包装类将保存计算结果,并且会有一个 boolean done 标志。等待线程将等待每个 Runnable 将它们的 done 标志设置为 true。当包装器完成其run() 方法时,它会在自身上设置donenotify()。它需要在 finally block 中执行此操作。

如果等待线程被中断,它会调用 executorService.shutdownNow(true) 来中断所有线程,但会继续循环等待它们完成。

类似的东西。

关于java - 如何中断 Future,但仍然等待它完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21068547/

相关文章:

c++ - 多线程中的临界区用法?

c - 中断时退出函数

Java线程输出数据到集合得到错误的结果

java - 为什么这不能形成一个好看的正方形?

java - intelliJ IDEA 中的自定义 spring 命名空间处理程序

java - 改变JAVA中对象的声明和构造

Java volatile 语义,JMM 保证

c++ - 等待句柄/事件异步或在同一线程内回调

c - STM32同一条EXTI线上的多个中断

Java 线程在 native 方法中阻塞等待 I/O 完成