gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:35 25 4
gpt4 key购买 nike

我有一系列使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com