-
CompletableFuture 是jdk8进入的一个异步变成工具,可以实现多线程编程。
-
下面记录了一次,多线程处理处理一个业务的例子,并且要等待所有异步子线程执行完成后,主线程才能继续往下执行。
-
supplyAsync:异步线程有返回值; runAsync:异步线程没返回值
@RestController
@RequestMapping(value = "/test")
public class ThreadController {
@Autowired
TaskService taskService;
private static final ExecutorService pool;
static {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("export-pool-%d") //线程名称
.build();
pool = new ThreadPoolExecutor(
4,
10,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(2048),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public void test() throws ExecutionException, InterruptedException {
List<CompletableFuture<String>> futrueList = new ArrayList<>();
for (int i = 0; i<10;i++){
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
String s = null;
try {
s = taskService.testThread("");
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("标记0:"+Thread.currentThread().getName());
return s;
}, pool);
futrueList.add(future);
}
System.out.println("标记1:"+Thread.currentThread().getName());
CompletableFuture.allOf(futrueList.toArray(new CompletableFuture[futrueList.size()])).join(); // 等待所有子线程的任务执行完毕
System.out.println("标记2:"+Thread.currentThread().getName());
for (CompletableFuture<String> fu : futrueList) {
System.out.println(fu.get());
}
}
运行结果: