future java get_java-当可运行对象引发异常时,Future.get()在单...

这里的复制品:

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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值