Код: Выделить всё
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletableFuture callbackHook = new CompletableFuture();
CompletableFuture future = CompletableFuture.runAsync(() -> {
try {
System.out.println("Starting Runnable");
while (true) {
System.out.println("still running");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// why is this code never getting hit?
System.err.println("InterruptedException caught in Runnable!");
callbackHook.complete(null);
}
}, executorService);
future.cancel(true);
callbackHook.get(); // this hangs forever...
System.out.println("*** DONE ***"); // this line is never reached
}
Код: Выделить всё
Starting Runnable
still running
still running
still running
still running
...(this continues forever)
И да, я знаю, что этот пример немного надуман, поскольку нет причин, по которым вам обязательно хотелось бы это сделать. ждать callbackHook вместо on в будущем, но есть и более сложные случаи, когда может использоваться такая логика — это всего лишь упрощенный пример.
Подробнее здесь: https://stackoverflow.com/questions/791 ... rlying-tas
Мобильная версия