我们如何在Java中将Callable编写为lambda表达式?
在 java.util.concurrent包中定义的Callable 接口。与只能运行线程的Runnable 接口相比,Callable 对象返回由线程完成的计算结果。该可调用 对象返回˚Future 对象提供的方法来监视线程执行的任务的进度。Future的 一个对象,用于检查Callable 接口的状态,并在线程完成后从Callable 检索结果。
在下面的示例中,我们可以将Callable 接口编写为Lambda Expression。
示例
import java.util.concurrent.*;
public class LambdaCallableTest {
public static void main(String args[]) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable c = () -> { // Lambda Expression int n = 0;
for(int i = 0; i < 100; i++) {
n += i;
}
return n;
};
Future<Integer> future = executor.submit(c);
try {
Integer result = future.get(); //wait for a thread to complete System.out.println(result);
} catch(ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
}输出结果
4950