나는 ExecutorService를 사용하여 큐에 대기하는 일련의 작업을 가지고있다. 사용자가 '취소'를 클릭하면 최대한 빨리 중단해야하는 작업을 알릴 필요가 있습니다. 그러나 때로는 부모 스레드가 진행되기 전에 완료해야하는 중요한 코드 섹션에 있습니다. 어떻게해야합니까? 나는 자기 자신의 취소 플래그를 사용하고 싶지는 않습니다. 왜냐하면 sleep/wait가 끝나지 않기 때문입니다. 미래를 방해하지만 어떻게 끝나기를 기다리는가?
는이 코드가 작동 것이라고 생각하지만, 내가하고 싶은 일을하지 않습니다 "가능한 한 빨리"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!
훌륭한 솔루션입니다. 나는 executorService.awaitTermination() 메소드에 대해 몰랐다. 그게 내가 원하는거야. –
그러나 자신의 작업 래퍼 사용에 대한 부분을 이해하지 못합니다.제 경우에는 결과가 필요 없습니다. 스레드가 끝날 때까지 기다릴 필요가 있습니다. 그래서 이것은 저에게 영향을주지 않습니다. 그러나 Future 객체를 사용하지 않고 ExecutorService를 사용하는 방법이 궁금합니다. 그 작업을 제출하는 유일한 API가 아닌가요? –
결과가 필요 없다면 훨씬 간단합니다. 'submit (...) '을 호출하면'Future'가되지만'void'를 반환하고'FutureTask' @ JesseBarnum을 생성하지 않는'execute (...)'를 호출 할 수도 있습니다. – Gray