Yes, you can replace flag
(or logically &&
) with !Thread.currentThread().isInterrupted()
.
This way, when the task is canceled, the loop will be terminated.
The loop would look something like this:
while(!Thread.currentThread().isInterrupted() && flag) {
/* Do work. */
}
Use should be something like this:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> task = executor.submit(new Task());
String str;
try {
str = task.get(5, TimeUnit.SECONDS);
} finally {
task.cancel(true);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…