取线程池里的结果
线程池里放 Callable
ExecutorService executorService = Executors. newCachedThreadPool();
Future future = executorService.submit(
new Callable<Double>() {
@Override
public Double call() throws Exception {
return doSomeLongTime();
}
}
);
doSomeElse();
try {
double result = ( double)future.get( 1,TimeUnit. SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
CompletableFuture
public static Future<Double> getPriceAsync() {
CompletableFuture<Double> future = new CompletableFuture<>();
new Thread(() -> {
double price = "A".charAt(0);
future.complete(price);
}).start();
return future;
}
Future<Double> future = getPriceAsync();
try {
double price = future.get();
System.out.println(price);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}