文章目录
多线程(Multithreading)是Java的一个特性,它可以允许一个程序的多个部分(也就是线程)并发地执行,以达到最大程度利用CPU的目的。
关于多线程编程(Multithread Programming),下面介绍一下Future
的特性和基本用法。
About Future
Future
(java.util.concurrent Interface Future<V>
)表示异步计算的结果。Future
接口提供了检查计算是否完成、检查计算是否被取消、等待计算完成并获取计算结果等方法。
A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
Future Methods
下面对Future
的几个方法做一下简要介绍并提供代码演示。
private static ExecutorService executor = Executors.newSingleThreadExecutor();
public static Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
Thread.sleep(3000);
return input * input;
});
}