vin*_*ddy 0 java parallel-processing asynchronous
我想知道未来的接口如何在java中实现异步执行.
Future<Map> xyz = [:]
Run Code Online (Sandbox Code Playgroud)
您需要使用Executors框架
创建ExecutorService,存在许多类型
ExecutorService executor = Executors.newFixedThreadPool(1);
Run Code Online (Sandbox Code Playgroud)
提交任务
Future<Integer> future = executor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
for (int i = 0; i < 1e9; i++) {
}
return 123;
}
});
Run Code Online (Sandbox Code Playgroud)
稍后,使用将来的参考来获得结果.一些可能的用途
future.isDone(); // check if ready
future.get(); // blocks until ready or InterruptedException
future.get(10, TimeUnit.SECONDS); // or wait a given time or TimeoutException
future.cancel(); // interrupt task
Run Code Online (Sandbox Code Playgroud)