我们如何在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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿