CompletableFuture
一、runAsync
1.1、runAsunc(一个Runnable接口)
package com.thread.study.jdksyn;
import java.util.concurrent.*;
/**
* @ClassName
* @Description TODO
* @Author ZQS
* @Date 2020/9/9 0009 14:29
* @Version 1.0
**/
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
System.out.println("当前线程为:" + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
voidCompletableFuture.get();
System.out.println("运行后再运行这个结果");
}
}
1.2、runAsync(一个Runnable接口,自定义线程池)
package com.thread.study.jdksyn;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName
* @Description TODO
* @Author ZQS
* @Date 2020/9/9 0009 14:29
* @Version 1.0
**/
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/**
* 自定义线程池
* ThreadFactory接口中只有一个方法
* Thread newThread(Runnable r);
*/
AtomicInteger atomicInteger = new AtomicInteger(0);
ExecutorService executorService = Executors.newFixedThreadPool(2,(runnable)->{
Thread thread=new Thread(runnable);
thread.setName("zqs_"+atomicInteger);
return thread;
});
/**
* 使用自定义线程池做完成异步编程
*/
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
System.out.println("当前线程为:" + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executorService);
voidCompletableFuture.get();
System.out.println("运行后再运行这个结果");
executorService.shutdown();
}
}
二、supplyAsync(有返回结果)
用法和runAsync 一样
有一个参
有两个参
package com.thread.study.jdksyn;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName
* @Description TODO
* @Author ZQS
* @Date 2020/9/9 0009 15:29
* @Version 1.0
**/
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/**
* 自定义线程池
*/
AtomicInteger atomicInteger = new AtomicInteger(0);
ExecutorService executorService =<