这里的复制品:
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("Hello!");
ExecutorService exec = Executors.newSingleThreadExecutor();
Future f = exec.submit(() -> x());
f.get();
System.out.println("f.get() returned");
exec.shutdownNow();
System.out.println("Good bye!");
}
private static Integer x() {
throw new RuntimeException("An unfortunate event");
}
}
输出仅显示“ Hello!”.和异常stacktrace,然后使程序永远挂起.
下面的更改可以解决该问题,但是您知道为什么执行挂在上面的代码中吗?
使用公共线程池不会挂起:
Future f = ForkJoinPool.commonPool().submit(() -> x());
将调用包裹在try / catch周围可以使应用程序正常退出:
Future f = exec.submit(() -> x());
try {
f.get();
} catch (Exception ex) {
ex.printStackTrace();
}