• Java高并发(线程创建以及线程池,异步调用,CompletableFuture)


    线程

    是进程中的一个实体,线程本身是不会独立存在的。
    进程是代码在数据集合上的一次运行活动 是系统进行资源分配调度的基本单位 。
    线程则是进程的一个执行路径, 一个进程中至少有 线程,进程中多个线程共享进程的资源。
    操作系统在分配资源时是把资源分配给进程的, 但是 CPU 资源 它是被分配到线程的,因为真正要占用CPU资源运行的是线程 所以也说线程是 CPU 分配的基本单位。

    创建线程

    • 继承Thread类
    • 实现Runnable接口
    • 使用Callable和Future创建线程
    • JDK8的Lambda创建线程
    /**
    	创建线程方式一:继承Thread
    		优点:在run方法中使用this就可以获取当前线程,无需Thread.currentThread()
    		缺点:不支持多继承,继承了Thread,不能继承其他类
    */
    public class ThreadTest{
    	public static class MyThread extends Thread{
    		@Override
    		public void run(){
    			System.out.println("I am a child thread");
    		}
    	}
    
    	public static void main(String[] args){
    		MyThread thread = new MyThread();
    		thread.start();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    /**
    	创建线程方式二:实现Runnable接口
    		优点:,两个线程共用task代码逻辑,如果需要,可以 RunableTask添加参数进行任务区分。
    		缺点:两种方式都没有返回值
    */
    public static class RunableTase implements Runnable{
    	@Override
    	public void run(){
    		System.out.println("I am a child thread");
    	}
    }
    
    public static void main(String[] args) throws InterruptedException{
    	RunableTask task = new RunableTask();
    	new Thread(task).start();
    	new Thread(task).start();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    /**
    	创建线程方式三:实现Callable接口
    */
    public static class CallerTase implements Callable<String>{
    	@Override
    	public String call() throws Excetion{
    		return "Hello";
    	}
    }
    
    public static void main(String[] args) throws InterruptedException{
    	//创建异步任务
    	FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
    	//启动线程
    	new Thread(futureTask).start();
    	try{
    		String result = futureTask.get();
    		System.out.println();
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    /**
    	使用JDK8的Lambda创建线程
    */
    new Thread(()-> System.out.println(Thread.currentThread().getName() + "在运行!")).start();
    
    • 1
    • 2
    • 3
    • 4

    Thread常用方法:

    一、构造方法创建线程
    在这里插入图片描述

    二、实例方法操作线程
    在这里插入图片描述

    关于join方法

    从运行结果可以得出一个结论,主线程main调用threadA.join()方法时,会进入阻塞状态,直到线程实例threadA的run()方法执行完毕,主线程main从阻塞状态变成可运行状态。
    此例中主线程main会无限期阻塞直到threadA.run()方法执行完毕。

    比如某个业务场景下,主线程main的执行时间是 1s,子线程的执行时间是 10s,同时主线程依赖子线程执行完的结果,此时让主线程执行join()方法进行适度阻塞,可以实现此目标。

    /**
    	join让调用此方法的主线程被阻塞,仅当该方法执行完成以后,才能继续运行
    */
    public class ThreadA extends Thread{
    	
    	@Override
    	public void run(){
    		
    		try{
    			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                System.out.println(time + " 当前线程:" + Thread.currentThread().getName() + ",正在运行");
                Thread.sleep(3000);
    		}catch(InterruptedException e){
    			e.printStackTrace();
    		}
    	}
    }
    
    
    public class ThreadTest{
    	
    	public static void main(String[] args) throws InterruptedException {
    		ThreadA threadA = new ThreadA();
            threadA.start();
    
            // 让执行这个方法的线程阻塞(指的是主线程,不是threadA线程)
            threadA.join();
    
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            System.out.println(time + " 主线程方法执行完毕!");
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    关于interrupt方法

    interrupt()方法的作用是当线程受到阻塞时,调用此方法会抛出一个中断信号,让线程退出阻塞状态,如果当前线程没有阻塞,是无法中断线程的。
    与此对应的还有isInterrupted()方法,用于检查线程是否已经中断,但不清除状态标识。

    public class ThreadA extends Thread {
    
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
                System.out.println(time + " 当前线程:" + Thread.currentThread().getName() + ",count:" + i);
            }
        }
    }
    
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            threadA.start();
    
            Thread.sleep(50);
    
            // 检查线程是否中断,没有尝试终止线程
            //如果当前线程没有阻塞,调用interrupt()起不到任何效果。
            //当线程处于阻塞状态时,调用interrupt()方法,可以让线程退出阻塞,起到终止线程的效果
            if(!threadA.isInterrupted()){
                threadA.interrupt();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    关于isAlive方法

    isAlive()方法的作用是检查线程是否处于活动状态,只要线程启动且没有终止,方法返回的就是true
    线程启动前isAlive=false,线程运行中isAlive=true,线程运行完成isAlive=false

    public class ThreadA extends Thread {
    
        @Override
        public void run() {
            System.out.println("当前线程:" + Thread.currentThread().getName() + ",isAlive:" + Thread.currentThread().isAlive());
        }
    }
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            System.out.println("begin == " + threadA.isAlive());
    
            threadA.start();
    
            Thread.sleep(1000);
            System.out.println("end == " + threadA.isAlive());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    三、静态方法

    线程类的构造方法、静态块是被主线程main调用的,而线程类的run()方法才是用户线程自己调用的
    在这里插入图片描述
    从运行结果可以看出,Thread.currentThread方法返回的未必是Thread本身,而是当前正在执行线程对象的引用,这和通过this.XXX()返回的对象是有区别的。

    public class ThreadA extends Thread {
    
        public ThreadA() {
            System.out.println("构造方法打印 Begin...");
            System.out.println("Thread.currentThread打印的线程名称:" + Thread.currentThread().getName());
            System.out.println("this.getName打印的线程名称:" + this.getName());
            System.out.println("构造方法打印 end...");
        }
    
        @Override
        public void run() {
            System.out.println("run()方法打印 Begin...");
            System.out.println("Thread.currentThread打印的线程名称:" + Thread.currentThread().getName());
            System.out.println("this.getName打印的线程名称:" + this.getName());
            System.out.println("run()方法打印 end...");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            System.out.println("===============");
            threadA.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    yield()
    暂停当前执行的线程对象,并执行其他线程。这个暂停会放弃 CPU 资源,并且放弃 CPU 的时间不确定,有可能刚放弃,就获得 CPU 资源了,也有可能放弃好一会儿,才会被 CPU 执行

    public class ThreadA extends Thread {
    
        private String name;
    
        public ThreadA(String name) {
            this.name = name;
        }
    	
    	//调用yield()方法可以让线程放弃 CPU 资源,循环次数越多,越明显
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(name  + ":" + i);
                if ("t1".equals(name)) {
                    System.out.println(name  + ":" + i +"......yield.............");
                    Thread.yield();
                }
            }
        }
    }
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA1 = new ThreadA("t1");
            ThreadA threadA2 = new ThreadA("t2");
    
            threadA1.start();
            threadA2.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    sleep方法
    指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。这个正在执行的线程指的是Thread.currentThread()返回的线程
    根据 JDK API 的说法,该线程不丢失任何监视器的所属权,换句话说就是不会释放锁,如果sleep()代码上下文被加锁了,锁依然在,只是 CPU 资源会让出给其他线程。

    public class ThreadA extends Thread {
    
        @Override
        public void run() {
            try {
                String begin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
                System.out.println(begin + " 当前线程:" + Thread.currentThread().getName());
    
                Thread.sleep(3000);
    
                String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
                System.out.println(end + " 当前线程:" + Thread.currentThread().getName());
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            threadA.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    holdsLock()方法
    表示当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true,简单的说就是检测一个线程是否拥有锁

    public class ThreadA extends Thread {
    
        private String lock = "lock";
    
        @Override
        public void run() {
            System.out.println("当前线程:" + Thread.currentThread().getName() + ",Holds Lock = " + Thread.holdsLock(lock));
    
            synchronized (lock){
                System.out.println("当前线程:" + Thread.currentThread().getName() + ",Holds Lock = " + Thread.holdsLock(lock));
            }
        }
    }
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            threadA.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    dumpStack方法
    是将当前线程的堆栈跟踪打印至标准错误流。此方法仅用于调试

    public class ThreadA extends Thread {
    
        @Override
        public void run() {
            System.out.println("当前线程:" + Thread.currentThread().getName());
            Thread.dumpStack();
        }
    }
    
    public class ThreadTest {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadA threadA = new ThreadA();
            threadA.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    =====================================================================

    Runnable无返回值

    public static void main(String[] args){
    	
    	Runnable hellos = () -> {
    		for(int i = 1; i <= 1000; i+){
    			System.out.println("Hello " + i);
    		}
    	};
    	Runnable goodbyes = () -> {
    		for(int i = 1; i <= 1000; i+){
    			System.out.println("Goodbye " + i);
    		}
    	};
    	
    	Executor executor = Executors.newCachedThreadPool();
    	executor.execute(hellos);
    	executor.execute(goodbyes); //结果是交叉输出
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Callable有返回值
    Future接口代表计算的结果,有如下方法

    • V get() 阻塞,知道有了可用结果或者超时,返回计算值。
    • V get(long timeout,TimeUnit.unit)
    • boolean cancel(boolean mayInterruptIfRunning) 取消任务。如果任务还未运行,就不会将任务列入运行计划。否则如果参数为true,则正在运行任务的线程会被中断
    • boolean isCancelled()
    • boolean isDone()
    //Executor的子接口ExecutorService
    ExecutorService exec = Executors.newFixedThreadPool();
    
    Callable<V> task = () -> {
    	while(){
    		if(Thread.currentThread().isInterrupted()){
    			return null;
    		}
    	}
    	return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    线程池
    在这里插入图片描述

    /**
    	线程池的创建:
    	corePoolSize(线程池的基本大小)当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,等到需要执行的任务数大于线程池基本大小时就不再创建。调用了线程池的prestartAllCoreThreads()方法,线程池会提前创建并启动所有基本线程
    	
    	maximumPoolSize(线程池最大数量)。如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。值得注意的是,如
    果使用了无界的任务队列这个参数就没什么效果。
    
    	keepAliveTime(线程活动保持时间)线程池的工作线程空闲后,保持存活的时间。所以,如果任务很多,并且每个任务执行的时间比较短,可以调大时间,提高线程的利用率
    	TimeUnit(线程活动保持时间的单位):可选的单位有天(DAYS)、小时(HOURS)、分钟(MINUTES)、毫秒(MILLISECONDS)、微秒(MICROSECONDS,千分之一毫秒)和纳秒(NANOSECONDS,千分之一微秒)
    	
    	runnableTaskQueue(任务队列):用于保存等待执行的任务的阻塞队列。
    		ArrayBlockingQueue:是一个基于数组结构的有界阻塞队列,此队列按FIFO(先进先出)原则对元素进行排序
    		LinkedBlockingQueue:一个基于链表结构的阻塞队列,此队列按FIFO排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法Executors.newFixedThreadPool()使用了这个队列
    		SynchronousQueue:一个不存储元素的阻塞队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于Linked-BlockingQueue,静态工厂方法Executors.newCachedThreadPool使用了这个队列
    		PriorityBlockingQueue:一个具有优先级的无限阻塞队列
    		
    	RejectedExecutionHandler(饱和策略):当队列和线程池都满了,说明线程池处于饱和状态,那么必须采取一种策略处理提交的新任务。这个策略默认情况下是AbortPolicy,表示无法处理新任务时抛出异常。
    		AbortPolicy:直接抛出异常
    		CallerRunsPolicy:只用调用者所在线程来运行任务
    		DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务
    		DiscardPolicy:不处理,丢弃掉
    
    */
    new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,milliseconds,runnableTaskQueue, handler);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    /**
    	向线程池提交任务:
    		execute()提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功
    		submit()用于提交需要返回值的任务线程池会返回一个future类型的对象,通过这个future对象可以判断任务是否执行成功,并且可以通过future的get()方法来获取返回值,get()方法会阻塞当前线程直到任务完成,而使用get(long timeout,TimeUnit unit)方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完
    */
    threadsPool.execute(new Runnable() {
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    	}
    });
    
    Future<Object> future = executor.submit(harReturnValuetask);
    try {
    	Object s = future.get();
    } catch (InterruptedException e) {
    	// 处理中断异常
    } catch (ExecutionException e) {
    	// 处理无法执行任务异常
    } finally {
    	// 关闭线程池(的shutdown或shutdownNow)
    	executor.shutdown();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    异步调用vs同步调用(Future)

    同步调用

    @Component
    public class Task{
    	
    	public static Random random = new Random();
    
    	public void doTaskOne() throws Exception{
    		
    		System.out.println("开始做任务一");
    		long start = System.currentTimeMillis();
    		Thread.sleep(random.nextInt(10000));
    		long end = System.currentTimeMillis();
    		System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
    	}
    
    	public void doTaskTwo() throws Exception {
            System.out.println("开始做任务二");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        }
    
        public void doTaskThree() throws Exception {
            System.out.println("开始做任务三");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = Application.class)
    public class ApplicationTests{
    	
    	@Autowired
    	private Task task;
    
    	@Test
    	public void test() throws Exception{
    		task.doTaskOne();
    		task.doTaskTwo();
    		task.doTaskThree();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    异步的八种实现方式:

    • 线程Thread
    • Future
    • 异步框架CompletableFuture
    • Spring注解@Async
    • Spring ApplicationEvent事件
    • 消息队列
    • 第三方异步框架,不如Hutool的ThreadUtil
    • Guava异步

    一、线程异步

    public class AsyncThread extends Thread{
    	
    	@Override
    	public void run(){
    		System.out.println("Current thread name:" + Thread.currentThread().getName() + " Send email success!");
    	}
    
    	/**
    		以上频繁创建、销毁线程浪费资源,采用线程池的方式,将业务逻辑封装到Runnable或callable中,交给线程池执行
    	*/
    	private ExecutorService executorService = Executors.newCachedThreadPool();
    	public void fun(){
    		
    		executorService.submit(new Runnable(){
    			@Override
    			public void run(){
    				log.info("执行业务逻辑……");
    			}
    		});
    	}
    
    	public static void main(String[] args){
    		AsyncThread asyThread = new AsyncThread();
    		asyncThread.run();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    二、Spring中的@Async异步

    指程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序。

    SpringBoot中通过注解@Async
    注:@Async所修饰的函数不要定义为static类型,这样异步调用不会生效

    @Component
    public class Task{
    	
    	@Async
    	public void doTaskOne() throws Exception{
    
    	}
    
    	@Async
        public void doTaskTwo() throws Exception {
            // 同上内容,省略
        }
    
        @Async
        public void doTaskThree() throws Exception {
            // 同上内容,省略
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    SpringBoot启动类@EnableAsync

    @SpringBootApplication
    @EnableAsync
    public class Application{
    	
    	public static void main(){
    		 SpringApplication.run(Application.class, args);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    继续反复执行单元测试,遇到各种不同的结果:

    • 没有任何任务相关的输出
    • 有部分任务相关的输出
    • 乱序的任务相关的输出

    原因是目前doTaskOne、doTaskTwo、doTaskThree三个函数的时候已经是异步执行了。主程序在异步调用之后,主程序并不会理会这三个函数是否执行完成了,由于没有其他需要执行的内容,所以程序就自动结束了,导致了不完整或是没有输出任务相关内容的情况

    为了让doTaskOne、doTaskTwo、doTaskThree能正常结束,假设我们需要统计一下三个任务并发执行共耗时多少,这就需要等到上述三个函数都完成调动之后记录时间,并计算结果。
    那么我们如何判断上述三个异步调用是否已经执行完成呢?我们需要使用Future来返回异步调用的结果,就像如下方式改造doTaskOne函数:

    @Async
    public Future<String> doTaskOne()throws Exception{
    	
    	System.out.println("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
    
    	return new AsyncResult<>("任务一完成");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    按照如上方式改造一下其他两个异步函数之后,下面我们改造一下测试用例,让测试在等待完成三个异步调用之后来做一些其他事情。

    @Test
    public void test() throws Exception {
    
        long start = System.currentTimeMillis();
    
        Future<String> task1 = task.doTaskOne();
        Future<String> task2 = task.doTaskTwo();
        Future<String> task3 = task.doTaskThree();
    
        while(true) {
            if(task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
            Thread.sleep(1000);
        }
    
        long end = System.currentTimeMillis();
    
        System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    执行一下上述的单元测试,可以看到如下结果:

    开始做任务一
    开始做任务二
    开始做任务三
    完成任务三,耗时:37毫秒
    完成任务二,耗时:3661毫秒
    完成任务一,耗时:7149毫秒
    任务全部完成,总耗时:8025毫秒

    案例二:

    /**
    	自定义异步线程池
    	线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
    */
    @EnableAsync
    @Configuration
    public class TaskPoolConfig{
    	
    	//自定义线程池
    	@Bean("taskExecutor")
    	public Executor taskExecutor(){
    		
    		int i = Runtime.getRuntime().availableProcessors();
    		System.out.println("系统最大线程数:" + i);
    		
    		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    		//核心线程池大小
    		executor.setCorePoolSize(16);
    		//最大线程数
    		executor.setMaxPoolSize(20);
    		//配置队列容量,默认值为Integer.MAX_VALUE
    		executor.setQueueCapacity(99999);
    		//活跃时间
    		executor.setKeepAliveSeconds(60);
    		//线程名称前缀
    		executor.setThreadNamePrefix("asyncServiceExecutor-");
    		//设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
    		executor.setAwaitTerminationSeconds(60);
    		//等待所有的任务结束后再关闭线程池
    		executor.setWaitForTasksToCompleteOnShutdown(true);
    		return executor;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    /**
    	实际项目中使用@Async调用线程池
    	推荐使用自定义线程池模式,不推荐直接使用@Async
    */
    public interface AsyncService{
    	
    	MessageResult sendSms(String callPrefix,String mobile,String actionType,String content);
    	MessageResult sendEmail(String email,String subject,String content);
    }
    
    
    @Slf4j
    @Service
    public class AsyncServiceImpl implements AsyncService{
    	
    	@Autowired
    	private IMessageHandler messageHandler;
    
    	@Override
    	@Async("taskExecutor")//调用自定义的线程池
    	public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content){
    		
    		try{
    			Thread.sleep(1000);
    			messageHandler.sendSms(callPrefix,mobile,actionType,content);
    		}catch(Exception e){
    			log.error("发送短信异常->",e);
    		}
    	}
    
    	@Override
    	@Async("taskExecutor")
    	 public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {
            try {
    
                Thread.sleep(1000);
                mesageHandler.sendSms(callPrefix, mobile, actionType, content);
    
            } catch (Exception e) {
                log.error("发送短信异常 -> ", e)
            }
        }
    
    	@Override
        @Async("taskExecutor")
        public sendEmail(String email, String subject, String content) {
            try {
    
                Thread.sleep(1000);
                mesageHandler.sendsendEmail(email, subject, content);
    
            } catch (Exception e) {
                log.error("发送email异常 -> ", e)
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    CompletableFuture

    在这里插入图片描述

    Future回顾

    使用Future.get()的方式阻塞调用线程,或者使用轮询方式判断 Future.isDone 任务是否结束,再获取结果

    @Test
    public void testFuture() throws ExecutionException,InterruptedException{
    	
    	ExecutorService.executorService = Executors.newFixedThreadPool(5);
    	Future<String> future = executorService.submit(() -> {
    		Thread.sleep(2000);
    		return "hello";
    	});
    
    	//Future.get()的方式阻塞调用线程,直到5个线程都执行结束
    	System.out.println(future.get());
    	System.out.println("end");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Future无法解决多个异步任务需要相互依赖的场景,简单点说就是,主线程需要等待子线程任务执行完毕之后在进行执行,想到了CountDownLatch,代码如下

    /**
    	定义两个Future,第一个通过用户id获取用户信息,第二个通过商品id获取商品信息
    */
    @Test
    public void testCountDownLatch() throws InterruptedExcetion,ExecutionException{
    	
    	ExecutorService executorService = Executors.newFixedThreadPool(5);
    	CountDownLatch downLatch = new CountDownLatch(2); //门阀初始化为2
    
    	long startTime = System.currentTimeMillis();
    	Future<String> userFuture = executorService.submit(() -> {
    		
    		Thread.sleep(500);//模拟查询商品耗时500毫秒
    		downLatch.countDown(); //初始化减一
    		return "用户A";
    	});
    
    	Future<String> goodsFuture = executorService.submit(() -> {
    		
    		Thread.sleep();//模拟查询商品耗时400毫秒
    		downLatch.countDown();
    		return "商品A";
    	});
    
    	downLatch.await();
    
    	//模拟主程序耗时时间
    	Thread.sleep(600);
    	System.out.println("获取用户信息:" + userFuture.get());
    	System.out.println("获取商品用户信息:" + goodsFuture.get());
    	System.out.println("总共用时:" + (System.currentTimeMilis() - startTime) + "ms");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    在这里插入图片描述
    不用异步操作,执行时间应该是:500+400+600 = 1500,用异步操作后实际只用1110。

    三、CompletableFuture实现异步

    @Test
    public void testCompletableInfo() throws InterruptedExcption,ExecutionException{
    	
    	//调用用户服务获取用户基本信息
    	CompletableFuture<String> userFuture = CompletableFuture.supplyAsync(() -> {
    		
    		try{
    			Thread.sleep(500);
    		}catch(InterruptedException e){
    			e.printStackTrace();
    		}
    		return "用户A";
    	});
    
    	//调用商品服务获取商品用户基本信息
    	CompletableFuture<String> goodsFuture = CompletableFuture.supplyAsync(() -> {
    		
    		try{
    			Thread.sleep(400);
    		}catch(InterruptedException e){
    			e.printStackTrance();
    		}
    
    		return "商品A";
    	});
    	
    	System.out.println("获取用户信息:" + userFuture.get());
    	System.out.println("获取商品信息:" + goodsFuture.get());
    
    	//模拟主程序耗时时间
    	Thread.sleep(600);
    	System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在这里插入图片描述
    通过CompletableFuture可以很轻松的实现CountDownLatch的功能。

    案例二

    public class CompletableFutureCompose{
    	
    	/**
    		thenAccept子任务和父任务公用一个线程
    		不需要显式使用ExecutorService,CompletableFuture 内部使用了ForkJoinPool来处理异步任务,如果在某些业务场景我们想自定义自己的异步线程池也是可以的。
    	*/
    	@SneakyThrows //就是利用了这一机制,将当前方法抛出的异常,包装成RuntimeException,骗过编译器,使得调用点可以不用显示处理异常信息
    	public static void thenRunAsync(){
    		
    		CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
    			
    			System.out.println(Thread.currentThread() + " cf1 do something....");
    			return 1;
    		});
    		
    		CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {
                System.out.println(Thread.currentThread() + " cf2 do something...");
            });
    		
    		//等待任务1执行完成
    		System.out.println("cf1结果->" + cf1.get());	
    		//等待任务2执行完成
            System.out.println("cf2结果->" + cf2.get());
    	}
    	
    
    	public static void main(String[] args){
    		thenRunAysnc();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    四种创建CompletableFuture的方式

    /**
    	CompletableFuture四个静态方法执行异步任务
    		supplyAsync 执行任务,支持返回值
    		runAsync 执行任务,没有返回值
    */
    
    //使用默认内置线程池ForkJoinPool.commonPool()  根据supplier构建执行任务
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier){..}  
    //自定义线程,根据supplier构建任务
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor){..}  
    
    //使用默认内置线程forkJoinPool.commonPool(),根据runnable构建执行任务
    public static CompletableFuture<Void> runAsync(Runnable runnable){..}  
    //自定义线程,根据runnable构建执行任务
    public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor){..}  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    四种获取CompltableFuture结果的方式

    //方式一  Future中已经提供
    public T get()  
    //方式二  提供了超时处理,如果在指定时间未获取结果将抛出超时异常
    public T get(long timeout, TimeUnit unit)  
    //方式三  立即获取结果不阻塞,结果计算已完成将返回结果获计算过程中的异常,如果未计算完成将返回设定的valueIfAbsent值
    public T getNow(T valueIfAbsent)   
    //方式四  方法里不会抛出异常
    public T join()  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    @Test
    public void testComplatableGet() throws InterruptedException,ExecutionException{
    
    	CompetableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
    		try{
    			Thread.sleep(1000);
    		}catch(InterruptedException e){
    			e.printStackTrace();
    		}
    		return "商品A";
    	});
    
    	//getNow方法测试
    	System.out.println(cp1.getNow("商品B"));//第一个执行结果为 「商品B」,因为要先睡上1秒结果不能立即获取
    
    	//join方法测试
    	CompletableFuture<Ineger> cp2 = CompletableFuture.supplyAsync((() -> 1/0));
    	System.out.println(cp2.join()); //join方法获取结果方法里不会抛异常,但是执行结果会抛异常,抛出的异常为CompletionException
    	System.out.println("-----------------------------------------------------");  
    
    	//get测试
    	ComplatableFuture<Integer> cp3 = CompletableFuture.supplyAsync((() -> 1/0));
    	System.out.println(cp3.get());//get方法获取结果方法里将抛出异常,执行结果抛出的异常为ExecutionException
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    异步回调方法

    在这里插入图片描述

    1、thenRun/thenRunAsync

    做完第一个任务后,再做第二个任务,第二个任务也没有返回值

    @Test
    public void testCompletableThenRunAsync() throws InterruptedException,ExecutionException{
    	
    	long startTime = System.currentTimeMillis();
    	CompletableFuture<Void> cp1 = CompletableFuture.runAsync(() -> {
    		
    		try{
    			//执行任务A
    			Thread.sleep(600);
    		}catch(InterruptedException e){
    			e.printStackTrace();
    		}
    	});
    
    	CompletableFuture<Void> cp2 = cp1.thenRun(() -> {
    		
    		try {  
                //执行任务B  
                Thread.sleep(400);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
    	});
    	
    	//get方法测试
    	System.out.println(cp2.get());
    
    	 //模拟主程序耗时时间  
        Thread.sleep(600);  
    
    	// 总共用时1610ms
        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    thenRun/thenRunAsync区别

    如果执行了第一个任务的时候,传入了一个自定义线程池:

    • 调用thenRun方法执行第二个任务时,则第二个任务和第一个任务公用同一个线程池
    • 调用thenRunAsync执行第二个任务时,则第一个任务使用的是自己传入的线程池,第二个任务使用的是ForkJoin线程池。
      说明: 后面介绍的thenAccept和thenAcceptAsync,thenApply和thenApplyAsync等,它们之间的区别也是这个。

    2、thenAccept/thenAcceptAsync

    第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果作为入参传递到回调方法中,回调方法没有返回值。

    @Test
    public void testCompletableThenAccept() throws ExecutionException,InterruptedException{
    	
    	 long startTime = System.currentTimeMillis();
    	 CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
    		return "dev";
    	});
    
    	CompletableFuture<Void> cp2 = cp1.thenAccept((a) -> {
    		System.out.println("上一个任务的返回结果为:" + a);
    	});
    
    	cp2.get();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3、 thenApply/thenApplyAsync

    表示第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果,作为入参,传递到回调方法中,并且回调方法是有返回值的.

    @Test
    public void testCompletableThenApply() throws ExecutionException,InterruptedException{
    	
    	CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
    		return "dev";
    	}).thenApply((a) -> {
    		if(Objects.equals(a,"dev")){
    			return "dev";
    		}
    		return "prod";
    	});
    
    	System.out.println("当前环境为:" + c1.get());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    4、异常回调whenComplete

    当CompletableFuture的任务不论是正常完成还是出现异常它都会调用 「whenComplete」这回调函数。

    • 正常完成:whenCompleta返回结果和上级任务一致,异常为null
    • 出现异常:whenCompleta返回结果为null,异常为上级任务的异常

    即调用get()时,正常完成时就获取到结果,出现异常时就会抛出异常,需要你处理该异常。

    @Test
    public void testCompletableWhenComplete() throws ExecutionException,InterruptedException{
    	
    	CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
    		
    		if(Math.random() < 0.5){
    			throw new RuntimeException("出错了");
    		}
    		System.out.println("正常结束");
    		return 0.11;
    	}).whenComplete((aDouble,throwable) -> {
    		
    		if(aDouble == null){
    			System.out.println("whenCompleta aDouble is null");
    		}        } else {  
                System.out.println("whenComplete aDouble is " + aDouble);  
            }  
            if (throwable == null) {  
                System.out.println("whenComplete throwable is null");  
            } else {  
                System.out.println("whenComplete throwable is " + throwable.getMessage());  
            }  
    
    	});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

    whenComplete+exceptionally

    当出现异常时,exceptionally中会捕获该异常,给出默认返回值0.0。

    @Test  
    public void testWhenCompleteExceptionally() throws ExecutionException, InterruptedException {
    	
    	CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {  
            if (Math.random() < 0.5) {  
                throw new RuntimeException("出错了");  
            }  
            System.out.println("正常结束");  
            return 0.11;  
    
        }).whenComplete((aDouble, throwable) -> {  
            if (aDouble == null) {  
                System.out.println("whenComplete aDouble is null");  
            } else {  
                System.out.println("whenComplete aDouble is " + aDouble);  
            }  
            if (throwable == null) {  
                System.out.println("whenComplete throwable is null");  
            } else {  
                System.out.println("whenComplete throwable is " + throwable.getMessage());  
            }  
        }).exceptionally((throwable) -> {  
            System.out.println("exceptionally中异常:" + throwable.getMessage());  
            return 0.0;  
    	});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在这里插入图片描述

    多任务组合回调

    在这里插入图片描述

    1、AND组合关系

    runAfterBoth、thenAcceptBoth、thenCombine:表示当任务一和任务二都完成在执行任务三。

    其区别:

    • reunAfterBoth 不会把执行结果当作方法入参,且没有返回值
    • thenAcceptBoth 会将两个任务的执行结果作为方法入参,传递到指定方法中,且无返回值
    • thenCombine 会将两个任务的执行结果作为方法入参,传递到指定方法中,且有返回值
    @Test  
    public void testCompletableThenCombine() throws ExecutionException, InterruptedException {
    	
    	//创建线程池
    	ExecutorService executorService = Executors.newFixedThreadPool(10);
    
    	//开启异步任务1
    	CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
    		
    		System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());
    		int result = 1 + 1;
    
    		System.out.println("异步任务1结束");
    		return result;
    	},exectorService);
    	
    	//开启异步任务2
    	CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
    	
    		System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());  
            int result = 1 + 1;  
            System.out.println("异步任务2结束");  
            return result; 
    	},executorService);
    
    	//任务组合
    	CompletableFuture<Integer> task3 = task.thenCombineAsync(task2,(f1,f2) -> {
    		
    		System.out.println("执行任务3,当前线程是:" + Thread.currentThread().getId());  
            System.out.println("任务1返回值:" + f1);  
            System.out.println("任务2返回值:" + f2);  
            return f1 + f2; 
    	},executorService);
    
    	Integer res = task3.get();  
        System.out.println("最终结果:" + res); 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    在这里插入图片描述

    2、OR组合关系

    runAfterEither、acceptEither、applyToEither 都表示两个任务只要有一个任务完成就执行任务三

    • runAfterEither 不会把执行结果当作方法入参,且没有返回值
    • acceptEither 会将已经完成的任务,作为方法入参,传递到指定方法中,且无返回值
    • applyToEither 会将已经执行完成的任务,作为方法入参,传递到指定方法中,且有返回值
    @Test  
    public void testCompletableEitherAsync() {  
    	
    	//创建线程池
    	ExecutorService executorService = Executors.newFixedThreadPool(10);
    
    	//开启异步任务1
    	CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
    		
    		 System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());  
    
            int result = 1 + 1;  
            System.out.println("异步任务1结束");  
            return result;  
    	},executorService);
    
    	//开启异步任务2  
        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {  
            System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());  
            int result = 1 + 2;  
            try {  
                Thread.sleep(3000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("异步任务2结束");  
            return result;  
        }, executorService);
    
    	//任务组合
    	task.acceptEitherAsync(task2,(res)->{
    		System.out.println("执行任务3,当前线程是:" + Thread.currentThread().getId());  
            System.out.println("上一个任务的结果为:"+res);  
    	},executorService);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    在这里插入图片描述

    如果把上面的核心线程数改为1也就是

    ExecutorService executorService = Executors.newFixedThreadPool(1);  
    
    • 1

    运行结果就是下面的了,会发现根本没有执行任务3,显然是任务3直接被丢弃了。
    在这里插入图片描述

    3、多任务组合

    「allOf」:等待所有任务完成
    「anyOf」:只要有一个任务完成

    @Test  
    public void testCompletableAallOf() throws ExecutionException, InterruptedException {  
    
    	//创建线程
    	ExecutorService executorService = Executors.newFixedThreadPool(10);
    	
    	//开启异步任务1
    	CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
    		 System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());  
            int result = 1 + 1;  
            System.out.println("异步任务1结束");  
            return result;  
    	},ececutorService);
    
    	 //开启异步任务2  
        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {  
            System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());  
            int result = 1 + 2;  
            try {  
                Thread.sleep(3000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("异步任务2结束");  
            return result;  
        }, executorService); 
    
    	//开启异步任务3  
        CompletableFuture<Integer> task3 = CompletableFuture.supplyAsync(() -> {  
            System.out.println("异步任务3,当前线程是:" + Thread.currentThread().getId());  
            int result = 1 + 3;  
            try {  
                Thread.sleep(4000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("异步任务3结束");  
            return result;  
        }, executorService);
    
    	//任务组合
    	CompletableFuture<Void> allOf = CompletableFuture.allOf(task,task2,task3);
    
    	//等待所有任务完成
    	allOf.get();
    
    	//获取所有任务的返回结果
    	System.out.println("task结果为:" + task.get());  
        System.out.println("task2结果为:" + task2.get());  
        System.out.println("task3结果为:" + task3.get());  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    @Test  
    public void testCompletableAnyOf() throws ExecutionException, InterruptedException {  
        //创建线程池  
        ExecutorService executorService = Executors.newFixedThreadPool(10);  
        //开启异步任务1  
        CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {  
            int result = 1 + 1;  
            return result;  
        }, executorService);  
    
        //开启异步任务2  
        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {  
            int result = 1 + 2;  
            return result;  
        }, executorService);  
    
        //开启异步任务3  
        CompletableFuture<Integer> task3 = CompletableFuture.supplyAsync(() -> {  
            int result = 1 + 3;  
            return result;  
        }, executorService);  
    
        //任务组合  
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(task, task2, task3);  
        //只要有一个有任务完成  
        Object o = anyOf.get();  
        System.out.println("完成的任务的结果:" + o);  
    }  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    在这里插入图片描述
    1、Future需要获取返回值,才能获取异常信息

    @Test  
    public void testWhenCompleteExceptionally() {  
        CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {  
            if (1 == 1) {  
                throw new RuntimeException("出错了");  
            }  
            return 0.11;  
        });  
    
        //如果不加 get()方法这一行,看不到异常信息  
        //future.get();  
    }  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Future需要获取返回值,才能获取到异常信息。如果不加 get()/join()方法,看不到异常信息。

    2、CompletableFuture的get()方法是阻塞的

    CompletableFuture的get()方法是阻塞的,如果使用它来获取异步调用的返回值,需要添加超时时间。

    //反例  
     CompletableFuture.get();  
    //正例  
    CompletableFuture.get(5, TimeUnit.SECONDS);  
    
    • 1
    • 2
    • 3
    • 4

    3、不建议使用默认线程池

    CompletableFuture代码中又使用了默认的 「ForkJoin线程池」,处理的线程个数是电脑 「CPU核数-1」。在大量请求过来的时候,处理逻辑复杂的话,响应会很慢。一般建议使用自定义线程池,优化线程池配置参数。

    4、自定义线程池时,注意饱和策略

    CompletableFuture的get()方法是阻塞的,我们一般建议使用future.get(5, TimeUnit.SECONDS)。并且一般建议使用自定义线程池。
    但是如果线程池拒绝策略是DiscardPolicy或者DiscardOldestPolicy,当线程池饱和时,会直接丢弃任务,不会抛弃异常。因此建议,CompletableFuture线程池策略最好使用AbortPolicy,然后耗时的异步线程,做好线程池隔离。

    ==================================================================

    四、Spring ApplicationEvent事件实现异步

    另外,可能有些时候采用ApplicationEvent实现异步的使用,当程序出现异常错误的时候,需要考虑补偿机制,那么这时候可以结合Spring Retry重试来帮助我们避免这种异常造成数据不一致问题。

    /**
    	定义事件
    */
    public class AsyncSendEmailEvent extends ApplicationEvent{
    	
    	 /**
         * 邮箱
         **/
        private String email;
    
       /**
         * 主题
         **/
        private String subject;
    
        /**
         * 内容
         **/
        private String content;
      
        /**
         * 接收者
         **/
        private String targetUserId;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    /**
    	定义事件处理器
    */
    @Slf4j
    @Component
    public class AsyncSendEmailEventHandler implements ApplicationListener<AsyncSendEmailEvent>{
    	
    	@Autowired
    	private IMessageHandler messageHandler;
    
    	@Async("taskExecutor")
    	@Override
    	public void onApplicationEvent(AsyncSendEmailEvent event){
    		
    		if(event == null){
    			return;
    		}
    		
    		String email = event.getEmail();
            String subject = event.getSubject();
            String content = event.getContent();
            String targetUserId = event.getTargetUserId();
            mesageHandler.sendsendEmailSms(email, subject, content, targerUserId);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    五、 消息队列

    /**
    	回调事件消息的生产者
    */
    @Slf4j
    @Component
    public class CallbackProducer{
    	
    	@Autowired
    	AmqpTemplate amqpTemplate;
    
    	public void sendCallbackMessage(CallbackDTO allbackDTO,final long delayTimes){
    		
    		log.info("生产者发送消息,callbackDTO,{}",callbackDTO);
    		
    		amqpTemplate.convertAndSend(CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getExchange(),
    							CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getRoutingKey(),
    							JsonMapper.getInstance().toJson(genseeCallbackDTO),
    							new MessagePostProcessor(){
    								
    								@Override
    								public Message postProcessMessage(Message message) throws AmqpException {
    									
    									//给消息设置延迟毫秒值,通过给消息设置x-delay头来设置消息从交换机发送到队列的延迟
    									message.getMessageProperties().setHeader("x-delay", delayTimes);
    									message.getMessageProperties().setCorrelationId(callbackDTO.getSdkId());
    									return message;
    								}
    							}		
    		);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    /**
    	回调事件消息消费者
    */
    @Slf4j
    @Component
    @RabitListener(queues = "message.callback", containerFactory = "rabbitListenerContainerFactory")
    public class CallbackConsumer{
    	
    	@Autowired
    	private IGlobalUserService globalUserService;
    
    	@RabbitHandler
    	public void handler(String json,Channel channel,@Headers Map<String,Object> map) throws Exception {
    		
    		if(map.get("error") != null){
    			//否认消息
    			channel.basicNack((Long) map.get(AmqpHeaders.DELIVERY_TAG),false,true);
    			return;
    		}
    
    		try{
    			CallbackDTO callbackDTO = JsonMapper.getInstance().fromJson(json, CallbackDTO.class);
    
    			//执行业务逻辑
    			globalUserService.execute(callbackDTO);
    			//消息成狗手动确认,对应消息确认模式acknowledge-model:manual
    			channel.basicAck((Long) map.get(AmqpHeaders.DELIVERY_TAG),false);
    		}catch(Exception e){
    			log.error(("回调失败 -> {}", e);
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    六、ThreadUtil异步工具类

    @Slf4j
    public class ThreadUtils{
    	
    	public static void main(String[] args){
    		
    		for(int i = 0;i<3;i++){
    			ThreadUtil.execAsync(() -> {
    				ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
    				int number = threadLocalRandom.nextInt(20) + 1;
    				System.out.println(number);
    			});
    			log.info("当前第:" + i + "个线程");
    		}
    		log.info("task finish!");
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    七、Guava异步

    Guava的ListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。
    使用Guava ListenableFuture可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。

    ListenableFuture是一个接口,它从jdk的Future接口继承,添加了void addListener(Runnable listener, Executor executor)方法。

    /**
    	通过MoreExecutors类的静态方法listeningDecorator方法初始化一个ListeningExecutorService的方法
    */
    ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    
    /**
    	使用此实例的submit方法即可初始化ListenableFuture对象
    */
    final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
                
                /**
                	ListenableFuture要做的工作,在Callable接口的实现类中定义,这里只是休眠了1秒钟然后返回一个数字1,有了ListenableFuture实例,可以执行此Future并执行Future完成之后的回调函数。
                */
                @Override
                public Integer call() throws Exception {
                    log.info("callable execute...")
                    TimeUnit.SECONDS.sleep(1);
                    return 1;
                }
            });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
     Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(Integer result) {
            //成功执行...
            System.out.println("Get listenable future's result with callback " + result);
        }
    
        @Override
        public void onFailure(Throwable t) {
            //异常情况处理...
            t.printStackTrace();
        }
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    =========================================================

    CompletableFuture的用法示例

    CompletionStage接口,相当于一个计算单元,几个CompletionStage串联起来,一个完成的阶段可以触发下一阶段的执行,接着触发下一次,接着……
    Future接口,代表一个未完成的异步事件

    CompletableFuture实现以上两个接口

    一、创建一个CompletableFuture

    static void completedFutureExample(){
    	CompletableFuture cf = CompletableFuture.completedFuture("message");
    	assertTrue(cf.isDone());
    
    	//在future完成的情况下会返回结果,否则返回null(传入的参数)
    	assertEquals("message",cf.getNow(null));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    二、运行一个简单的异步阶段

    static void runAsyncExample(){
    
    	//方法如果以Async结尾,它会异步的执行(没有指定executor的情况下), 异步执行通过ForkJoinPool实现, 它使用守护线程去执行任务
    	CompletableFuture cf = CompletableFuture.runAsync(() -> {
    		assertTrue(Thread.currentThread().isDaemon());
    		randomSleep();
    	});
    
    	assertFalse(cf.idDone());
    	sleepEnough();
    	assertTrue(cf.idDone());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    三、在前一个阶段上应用函数

    下面这个例子使用前面 #1 的完成的CompletableFuture, #1返回结果为字符串message,然后应用一个函数把它变成大写字母。

    static void thenApplyExample(){
    	
    	CompletableFuture cf = CompletableFuture.completedFuture("message").thenApply(
    		s -> {
    			assertFalse(Thread.currentThread().isDaemon());
    			return s.toUpperCase();
    		}
    	);
    	assertEquals("MESSAGE",cf.getNow(null));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    tuehApply方法

    • then意味着这个阶段的动作发生当前的阶段正常完成之后。本例中,当前节点完成,返回字符串message
    • Apply意味着返回的阶段将会对结果前一阶段的结果应用一个函数

    函数的执行会被阻塞,意味着getNow()只有当前操作被完成后才返回

    四、在前一个阶段上异步应用函数

    通过异步调用方法(方法后面添加Async后缀),串联起来的CompletableFuture可以异步执行
    (使用ForkJoinPool.commonPool())

    static void thenApplyAsyncExample(){
    	CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(
    		s -> {
    			assertTrue(Thread.currentThread().isDaemon());
    			randomSleep();
    			return s.toUpperCase();
    		}
    	);
    	assertNull(cf.getNow(null));
    	assertEquals("MESSAGE",cf.join());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    五、使用定制的Executor在前一个阶段上异步应用函数

    异步方法一个非常有用的特性就是能够提供一个Executor来异步地执行CompletableFuture

    如何使用一个固定大小的线程池来应用大写函数。

    static ExecutorService executor = Executors.newFixedThreadPool(3,new ThreadFactory(){
    
    	int count = 1;
    
    	@Override
    	public Thread newThread(Runnable runnable){
    		return new Thread(runnable,"custom-executor-" + count++);
    	}
    });
    
    static void thenApplyAsyncWithExecutorExample(){
    	
    	CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(
    		s -> {
    			assertTrue(Thread.currentThread().getName().startsWith("custom-executor-"));
    			assertFalse(Thread.currentThread().isDaemon());
    			randomSleep();
    			return s.toUpperCase();
    		},executor
    	);
    	assertNull(cf.getNow(null));
    	assertEquals("MESSAGE",cf.join());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    六、消费前一阶段的结果

    如果下一阶段接收了当前阶段的结果,但是在计算的时候不需要返回值(它的返回类型是void), 那么它可以不应用一个函数,而是一个消费者, 调用方法也变成了thenAccept:

    static void theAcceptExample(){
    	StringBuilder result = new StringBuilder();
    
    	CompletableFuture.completedFuture("thenAccept message")
    		.thenAccept(s -> result.append(s));
    
    	assertTrue("Result was Empty",result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    消费者同步地执行,所以我们不需要在CompletableFuture调用join方法

    七、异步地消费迁移阶段的结果

    同样,可以使用thenAcceptAsync方法, 串联的CompletableFuture可以异步地执行

    static void thenAcceptAsyncExample(){
    	
    	StringBuilder result = new StringBuilder();
    	CompletableFuture cf = Completable.completedFuture("thenAcceptAsync message")
    		.thenAcceptAsync(s -> result.append(s));
    	
    	cf.join();
    	assertTrue("Result was empty",result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    八、完成计算异常

    使用thenApplyAsync(Function, Executor)方法,第一个参数传入大写函数, executor是一个delayed executor,在执行前会延迟一秒

    static void completeExceptionallyExample(){
    	
    	/**
    		创建了一个CompletableFuture, 完成后返回一个字符串message,接着我们调用thenApplyAsync方法,它返回一个CompletableFuture。
    		这个方法在第一个函数完成后,异步地应用转大写字母函数
    		通过delayedExecutor(timeout, timeUnit)延迟执行一个异步任务
    	*/
    	CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
                CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
    
    	/**
    		创建了一个分离的handler阶段:exceptionHandler, 它处理异常异常,在异常情况下返回message upon cancel
    	*/
    	CompletableFuture exceptionHandler = cf.handle((s, th) -> {
    	
    		 return (th != null) ? "message upon cancel" : "";
    	});
    	
    	/**
    		显式地用异常完成第二个阶段。
    		在阶段上调用join方法,它会执行大写转换,然后抛出CompletionException(正常的join会等待1秒,然后得到大写的字符串。
    		不过我们的例子还没等它执行就完成了异常), 然后它触发了handler阶段
    	*/
    	cf.completeExceptionally(new RuntimeException("completed exceptionally"));
    	assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
    	
    	try{
    		cf.join();
    		fail("Should have thrown an exception");
    	}catch(CompletionException ex){
    		assertEquals("completed exceptionally", ex.getCause().getMessage());
    	}
    	assertEquals("message upon cancel", exceptionHandler.join());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    九、取消计算

    调用cancel(boolean mayInterruptIfRunning)取消计算
    对于CompletableFuture类,布尔参数并没有被使用,这是因为它并没有使用中断去取消操作,相反,cancel等价于completeExceptionally(new CancellationException())

    static void cancelExample(){
    	
    	Completable cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
                CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
    	
    	CompletableFuture cf2 = cf.exceptionally(throwable -> "canceled message");
    	assertTrue("Was not canceled", cf.cancel(true));
    	assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
    	assertEquals("canceled message", cf2.join());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    十、在两个完成的阶段之一上应用函数

    创建了CompletableFuture, applyToEither处理两个阶段, 在其中之一上应用函数(包保证哪一个被执行)。本例中的两个阶段一个是应用大写转换在原始的字符串上, 另一个阶段是应用小些转换。

    static void applyToEitherExample(){
    	
    	String original = "Message";
    	CompletableFuture cf1 = CompletebleFuture.completedFuture(original)
    		.thenApplyAsync(s -> delayedUpperCase(s));
    	
    	CompletableFuture cf2 = cfq.applyToEither(CompletableFuture.completedFuture(pritinal).thenApplyAsync(s -> delayedLowerCase(s)),s -> s + " from applyToEither");
    
    	assertTrue(cf2.join().endsWith(" from applyToEither"));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    十一、在两个完成的阶段其中之一上调用消费函数

    static void acceptEitherExample(){
    	
    	String original = "Message";
    	StringBuilder result = new StringBuilder();
    	CompetableFuture cf = CompletableFuture.completedFuture(original)
    		.thenApplyAsync(s -> delayedUpperCase(s))
    		.acceptEither(CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
                        s -> result.append(s).append("acceptEither"));
    	cf.join();
    	assertTrue("Result was empty", result.toString().endsWith("acceptEither"));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    十二、在两个阶段都执行完后运行一个Runnable

    依赖的CompletableFuture如果等待两个阶段完成后执行了一个Runnable。

    注意下面所有的阶段都是同步执行的,第一个阶段执行大写转换,第二个阶段执行小写转换

    static void runAfterBothExample(){
    	String oritinal = "Message";
    	StringBuilder result = new StringBuilder();
    
    	 CompletableFuture.completedFuture(original).thenApply(String::toUpperCase).runAfterBoth(
                CompletableFuture.completedFuture(original).thenApply(String::toLowerCase),
                () -> result.append("done"));
        assertTrue("Result was empty", result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    十三、使用BiConsumer处理两个阶段的结果

    static void thenAcceptBothExample(){
    	
    	String original = "Message";
    	StringBuilder result = new StringBuilder();
    	CompletableFuture.completedFuture(original).thenApply(String::toUpperCase).thenAcceptBoth( CompletableFuture.completedFuture(original).thenApply(String::toLowerCase),
                (s1, s2) -> result.append(s1 + s2));
    
    	assertEquals("MESSAGEmessage", result.toString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    十四、使用BiFunction处理两个阶段的结果

    如果CompletableFuture依赖两个前面阶段的结果, 它复合两个阶段的结果再返回一个结果,我们就可以使用thenCombine()函数。整个流水线是同步的,所以getNow()会得到最终的结果,它把大写和小写字符串连接起来。

    static void thenCombineExample(){
    	String original = "Message";
    
    	CompletableFuture cf = CompletableFuture.completedFuture(original).thenApply(s -> delayedUpperCase(s))
                .thenCombine(CompletableFuture.completedFuture(original).thenApply(s -> delayedLowerCase(s)),
                        (s1, s2) -> s1 + s2);
    	assertEquals("MESSAGEmessage", cf.getNow(null));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    十五、异步使用BiFunction处理两个阶段的结果

    类似上面的例子,但是有一点不同:依赖的前两个阶段异步地执行,所以thenCombine()也异步地执行,即时它没有Async后缀

    static void thenCombineAsyncExcample(){
    	
    	String original = "Message";
    	CompletableFuture cf = CompletableFuture.completedFuture(original)
    		.thenApplyAsync(s -> delayedUpperCase(s))
    		.thenCombine(CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
                        (s1, s2) -> s1 + s2);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    十六、组合CompletableFuture

    使用thenCompose()完成上面两个例子。这个方法等待第一个阶段的完成(大写转换), 它的结果传给一个指定的返回CompletableFuture函数,它的结果就是返回的CompletableFuture的结果。

    有点拗口,但是我们看例子来理解。函数需要一个大写字符串做参数,然后返回一个CompletableFuture, 这个CompletableFuture会转换字符串变成小写然后连接在大写字符串的后面。

    static void thenComposeExample(){
    
    	String priginal = "Message";
    	CompletableFuture cf = CompletableFuture.completedFuture(original).thenApply(s -> delayedUpperCase(s))
                .thenCompose(upper -> CompletableFuture.completedFuture(original).thenApply(s -> delayedLowerCase(s))
                        .thenApply(s -> upper + s));
        assertEquals("MESSAGEmessage", cf.join());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    十七、当几个阶段中的一个完成,创建一个完成的阶段

    当任意一个CompletableFuture完成后, 创建一个完成的CompletableFuture.

    待处理的阶段首先创建, 每个阶段都是转换一个字符串为大写。因为本例中这些阶段都是同步地执行(thenApply), 从anyOf中创建的CompletableFuture会立即完成,这样所有的阶段都已完成,我们使用whenComplete(BiConsumer action)处理完成的结果。

    static void anyOfExample() {
        StringBuilder result = new StringBuilder();
        List messages = Arrays.asList("a", "b", "c");
        List<CompletableFuture> futures = messages.stream()
                .map(msg -> CompletableFuture.completedFuture(msg).thenApply(s -> delayedUpperCase(s)))
                .collect(Collectors.toList());
        CompletableFuture.anyOf(futures.toArray(new CompletableFuture[futures.size()])).whenComplete((res, th) -> {
            if(th == null) {
                assertTrue(isUpperCase((String) res));
                result.append(res);
            }
        });
        assertTrue("Result was empty", result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    十八、当所有的阶段都完成后创建一个阶段

    当任意一个阶段完成后接着处理,接下来的两个例子演示当所有的阶段完成后才继续处理, 同步地方式和异步地方式两种。

    static void allOfExample() {
        StringBuilder result = new StringBuilder();
        List messages = Arrays.asList("a", "b", "c");
        List<CompletableFuture> futures = messages.stream()
                .map(msg -> CompletableFuture.completedFuture(msg).thenApply(s -> delayedUpperCase(s)))
                .collect(Collectors.toList());
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).whenComplete((v, th) -> {
            futures.forEach(cf -> assertTrue(isUpperCase(cf.getNow(null))));
            result.append("done");
        });
        assertTrue("Result was empty", result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    十九、当所有的阶段都完成后异步地创建一个阶段

    使用thenApplyAsync()替换那些单个的CompletableFutures的方法,allOf()会在通用池中的线程中异步地执行。所以我们需要调用join方法等待它完成。

    static void allOfAsyncExample() {
        StringBuilder result = new StringBuilder();
        List messages = Arrays.asList("a", "b", "c");
        List<CompletableFuture> futures = messages.stream()
                .map(msg -> CompletableFuture.completedFuture(msg).thenApplyAsync(s -> delayedUpperCase(s)))
                .collect(Collectors.toList());
        CompletableFuture allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
                .whenComplete((v, th) -> {
                    futures.forEach(cf -> assertTrue(isUpperCase(cf.getNow(null))));
                    result.append("done");
                });
        allOf.join();
        assertTrue("Result was empty", result.length() > 0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    二十、实践场景

    1. 首先异步调用cars方法获得Car的列表,它返回CompletionStage场景。cars消费一个远程的REST API。
    2. 然后我们复合一个CompletionStage填写每个汽车的评分,通过rating(manufacturerId)返回一个CompletionStage, 它会异步地获取汽车的评分(可能又是一个REST API调用)
    3. 当所有的汽车填好评分后,我们结束这个列表,所以我们调用allOf得到最终的阶段, 它在前面阶段所有阶段完成后才完成。
    4. 在最终的阶段调用whenComplete(),我们打印出每个汽车和它的评分。
    cars().thenCompose(cars -> {
        List<CompletionStage> updatedCars = cars.stream()
                .map(car -> rating(car.manufacturerId).thenApply(r -> {
                    car.setRating(r);
                    return car;
                })).collect(Collectors.toList());
     
        CompletableFuture done = CompletableFuture
                .allOf(updatedCars.toArray(new CompletableFuture[updatedCars.size()]));
        return done.thenApply(v -> updatedCars.stream().map(CompletionStage::toCompletableFuture)
                .map(CompletableFuture::join).collect(Collectors.toList()));
    }).whenComplete((cars, th) -> {
        if (th == null) {
            cars.forEach(System.out::println);
        } else {
            throw new RuntimeException(th);
        }
    }).toCompletableFuture().join();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    因为每个汽车的实例都是独立的,得到每个汽车的评分都可以异步地执行,这会提高系统的性能(延迟),而且,等待所有的汽车评分被处理使用的是allOf方法,而不是手工的线程等待(Thread#join() 或 a CountDownLatch)

  • 相关阅读:
    嵌入式Linux系统中ARM汇编语言的使用方法
    人活着最重要的是什么
    DayDayUp:计算机技术与软件专业技术资格证书之《系统集成项目管理工程师》课程讲解之十大知识领域之4核心—项目范围管理
    JavaWeb简单实例——DBCP数据库连接池
    Linux安装各种应用服务程序
    宋明的结局揭示了什么
    TensorFlow入门(七、检查点)
    leetcode 21. 合并两个有序链表(可进阶)
    js的数组如何根据元素内容删除
    软件定制开发的细节|网站搭建|APP小程序定制
  • 原文地址:https://blog.csdn.net/usa_washington/article/details/130798204