我正在尝试编写一个方法来创建一个线程,该线程在该方法已经返回后可以工作。我需要这个线程在一定时间后超时。
我有一个可行的解决方案,但我不确定这是否是最好的方法。
new Thread(() -> {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable() {
public Void call() throws Exception {
workThatTakesALongTime();
});
try {
future.get(timeoutMillis, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LOGGER.error("Exception from timeout.", e);
}
}).start();
有没有更好的方法来做到这一点而不使用线程中的 ExecutorService ?
ABOUTYOU
九州编程
相关分类