各位大佬,为什么这里 map 里面 x->逻辑
这种写法就没有问题,而 x->{逻辑}
这种写法就会报错呢?
代码如下图:
这样会报错:
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<String>> futures = new ArrayList<>();
System.out.println("32323223");
List<Integer> list = Arrays.asList(1, 2, 3);
List<String> collect = list.stream().map(x -> {
CompletableFuture.supplyAsync(() -> {
System.out.println("执行开始:" + new Date());
// 睡眠一秒,模仿处理过程
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行结束:" + new Date());
return new Date().toString();
}, executorService);
}
).map(CompletableFuture::join).collect(Collectors.toList());
executorService.shutdown();
System.out.println(collect);
System.out.println("77819");
}
这样不会:
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<String>> futures = new ArrayList<>();
System.out.println("32323223");
List<Integer> list = Arrays.asList(1, 2, 3);
List<String> collect = list.stream().map(x ->
CompletableFuture.supplyAsync(() -> {
System.out.println("执行开始:" + new Date());
// 睡眠一秒,模仿处理过程
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行结束:" + new Date());
return new Date().toString();
}, executorService)
).map(CompletableFuture::join).collect(Collectors.toList());
executorService.shutdown();
System.out.println(collect);
System.out.println("77819");
}
因为你没 return 啊……
是
的缩写。你写成
当然不对了。