Future<T>是一种任务,可以使用CompleteFuture<T>代替Future<T>。
CompleteFuture<T>的介绍:
https://blog.csdn.net/qq_34562093/article/details/90209520
https://www.cnblogs.com/TS86/p/18205735
package com.example.demo.basicSE;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
// Future<T> f = executorService.submit(new Callable<T>),但f.get()是阻塞的(CompletableFuture.get()也是阻塞的)
// 一般使用CompletableFuture替代Future:https://blog.csdn.net/qq_34562093/article/details/90209520
// CompletionService和CompletableFuture(按照任务完成的先后顺序获取任务的结果)
public class threads {
public static void _future() throws InterruptedException, ExecutionException{
List<Integer> list = List.of(1, 2, 3, 4, 5);
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Integer>> futures = new ArrayList<>();
for (int i : list) {
Future<Integer> future = executorService.submit(new createSqre(i));
futures.add(future);
}
List<Integer> res = new ArrayList<>();
for(Future<Integer> f:futures){
int t = f.get();
res.add(t);
}
for(int i:res){
System.out.println(i);
}
// shutdown()只是关闭了外部的submit(),线程池内部未执行完的还会继续跑
executorService.shutdown();
try {
// shutdownNow()立即停止线程池,正在跑的和等待的都停止了,但风险较大
// awaitTermination()后外部可以继续submit()进线程池。当前线程阻塞直到所有已提交任务跑完/超时/线程Interrupt()。
// 使用awaitTermination()来等待线程池中所有任务都执行完毕
if(!executorService.awaitTermination(60, TimeUnit.SECONDS)){
executorService.shutdownNow();
}
} catch (Exception e) {
// TODO: handle exception
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
public static int math_square(int x){
return x*x;
}
public static void _completeFuture(){
List<Integer> l = List.of(1,2,3,4,5);
// supplyAsync()异步处理
List<CompletableFuture<Integer>> futures = l.stream().map(i->CompletableFuture.supplyAsync(()->math_square(i))).collect(Collectors.toList());
// allof()等待所有future执行完成
CompletableFuture<Void> aCompletableFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
// 等待所有任务完成
aCompletableFuture.join();
List<Integer> ans = futures.stream().map(f->{
try {
return f.get();
} catch (Exception e) {
throw new IllegalStateException(e);
// TODO: handle exception
}
}).collect(Collectors.toList());
ans.forEach(System.out::println);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
// _future();
_completeFuture();
}
}
class createSqre implements Callable<Integer>{
private int n;
createSqre(int a){this.n = a;}
@Override
public Integer call() throws Exception {
return n*n;
}
}
浙公网安备 33010602011771号