1.异步处理是什么
- 在默认情况下,一个进程只包含一个线程,即从程序的开始,一直执行到结束。
- 其实线程是可以派生其他线程,在任意时刻,一个进程都可以包含不同状态的多个线程,来执行程序的不同部分。
- 如果一个进程拥有一个线程,它们将共享进程的资源。
- 系统为处理器规划的执行单元,是线程而非进程。
简而言之:异步编程相对于单体线程而言,不像单体编程那样等上面的代码执行完才能执行下面的 ,他是可以同时多部分一起进行运行的,在代码运行过程能大大节省时间提升效率;
2. CompletableFuture 理解
CompletableFuture的方法是比较重要的我们这边单独讲下:
CompletableFuture 提供了四个静态方法来创建一个异步操作。
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
3.runAsync与supplyAsync的区别
在开启异步时会有2种方式 分别是 runAsync 和 supplyAsync
- CompletableFuture.runAsync:无返回值,不使用自定义线程池时,使用默认线程池ForkJoinPool.commonPool
- CompletableFuture.supplyAsync:有返回值,不使用自定义线程池时,使用默认线程池ForkJoinPool.commonPool
4. allOf 和 anyOf 的区别
- allOf 等待所有的 CompletableFuture 结束。
- anyOf 则是只要有任意一个 CompletableFuture 结束,就可以做 接下来的事情,而无须像 AllOf 那样,等待所有的 CompletableFuture 结束。
5. 代码示例
import java.text.SimpleDateFormat;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//同步方式
notAsync();
//异步方式
//async();
}
public static void notAsync(){
System.out.println("---------------------------notAsync方法开始运行-----------------------------");
//获取开始时间(用来统计程序运行时常)
long t1 = System.currentTimeMillis();
//方法一
int callSum1 = call(1, 2);
//方法一