我们如何在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
热门推荐
10 上级买车祝福语大全简短
11 结业蛋糕男生祝福语简短
12 18岁的祝福语简短
13 怎样给人送祝福语简短
14 生日祝福语男孩 简短独特
15 幼儿住院祝福语老师简短
16 送给姐姐简短的祝福语
17 生日祝福语短句简短霸气
18 新年的生日祝福语简短