我们如何在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 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短