在Java中构建完整未来的最佳方法是什么?我已经CompletedFuture在下面实现了自己,但希望这样的东西已经存在.
public class CompletedFuture<T> implements Future<T> {
private final T result;
public CompletedFuture(final T result) {
this.result = result;
}
@Override
public boolean cancel(final boolean b) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
return this.result;
}
@Override
public T get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*ejs 167
在Java 8中,您可以使用内置的CompletableFuture:
Future future = CompletableFuture.completedFuture(value);
Run Code Online (Sandbox Code Playgroud)
hoa*_*oaz 59
Apache Commons Lang定义了类似的实现,称为ConstantFuture,您可以通过调用它来获取它:
Future<T> future = ConcurrentUtils.constantFuture(T myValue);
Run Code Online (Sandbox Code Playgroud)
FutureTask<String> ft = new FutureTask<>(() -> "foo");
ft.run();
System.out.println(ft.get());
Run Code Online (Sandbox Code Playgroud)
将打印出“foo”;
您还可以让 Future 在调用 get() 时抛出异常:
FutureTask<String> ft = new FutureTask<>(() -> {throw new RuntimeException("exception!");});
ft.run();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38776 次 |
| 最近记录: |