JDK8 多線程 JUC之CompletableFuture使用

package com.chezhibao.mockserver.mulitithread;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author hepei
 * @date 2019/8/26 10:05
 **/
@Slf4j
public class CompletableFutureDemo {

    /***
     * 無返回值
     */
    private static void runAsync() throws ExecutionException, InterruptedException {
        log.info("start ...{}",  System.currentTimeMillis()  );
        CompletableFuture<Void> future = CompletableFuture.runAsync( () -> {
            try {
                TimeUnit.SECONDS.sleep( 1 );
            } catch (InterruptedException ignored) {
            }
            log.info("end .....{}",  System.currentTimeMillis()  );
        } );
        future.get();
    }

    /***
     * 有返回值
     */
    private static void supplyAsync() throws ExecutionException, InterruptedException {
        log.info("start ...{}",  System.currentTimeMillis()  );
        CompletableFuture<Long> future = CompletableFuture.supplyAsync( () -> {
            try {
                TimeUnit.SECONDS.sleep( 1 );
            } catch (InterruptedException ignored) {
            }
            log.info("end .....{}",  System.currentTimeMillis()  );
            return System.currentTimeMillis();
        } );

        Long aLong = future.get();
        log.info("currentTime:{}",  System.currentTimeMillis());
    }


    private static void whenComplete() throws InterruptedException {
        CompletableFuture<Void> future = CompletableFuture.runAsync( () -> {
            try {
                TimeUnit.SECONDS.sleep( 1 );
            } catch (InterruptedException ignored) {
            }
            log.info("start ...{}",  System.currentTimeMillis()  );
            int i = 1 / 0;
        } );
        // 執行當前任務的線程執行繼續執行 whenComplete 的任務
        future.whenComplete( (aVoid, throwable) -> log.info("執行完成{}", throwable.getMessage()) );
        //當future執行發生異常後執行
        future.exceptionally( throwable -> {
            log.info("執行發生異常:{}", throwable.getMessage());
            return null;
        } );
        TimeUnit.SECONDS.sleep( 2 );
    }

    /***
     * 第二個任務依賴第一個任務的結果
     * thenApply 只可以執行正常的任務,任務出現異常則不執行 thenApply 方法
     */
    private static void thenApply() throws ExecutionException, InterruptedException {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync( () -> {
            long data = new Random().nextInt( 100 );
            log.info("data1=:{}", data);
            return data;
        } ).thenApply( t -> {
            long data = t * 10;
            log.info("data2=:{}", data);
            return data;
        } ).exceptionally( throwable -> {
            log.info("執行發生異常:{}", throwable.getMessage());
            return 0L;
        } );
        long result = future.get();
        log.info("thenApply執行結果:{}", result);
    }

    /***
     * 任務完成後再執行,還可以處理異常的任務
     */
    private static void handle() throws ExecutionException, InterruptedException {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync( () -> {
            int i = 10 / 0;
            return new Random().nextLong();
        } ).handle( (param, throwable) -> {
            Long result = -1L;
            if (throwable == null) {
                result = param * 10;
            } else {
                log.info("執行發生異常:{}", throwable.getMessage());
            }
            return result;
        } );
        log.info("handle執行結果:{}", future.get());
    }

    /***
     * 接收任務的處理結果,並消費處理,無返回結果。
     */
    private static void thenAccept() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future = CompletableFuture.supplyAsync( () -> new Random().nextInt( 1000 ) ).
                thenAccept( aLong -> log.info("thenAccept接收aLong值:{}",aLong) );
        future.get();
    }

    /***
     * 不關心任務的處理結果。只要上面的任務執行完成,就開始執行 thenRun 。
     */
    private static void thenRun() throws ExecutionException, InterruptedException {
        CompletableFuture future = CompletableFuture.supplyAsync( () -> new Random().nextInt( 10 ) ).thenRun( () ->  log.info("開始執行thenRun()"));
        future.get();
    }

    /***
     * 把兩個任務的結果一塊交給 thenCombine 來處理
     */
    private static void thenCombine() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync( () -> "then" );
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync( () -> "Combine" );
        CompletableFuture<String> data = future1.thenCombine( future2, (s, s2) -> s + " " + s2 );
        log.info("thenCombine執行結果:{}",data.get());
    }

    /***
     * 當兩個CompletionStage都執行完成後,把結果一塊交給thenAcceptBoth來進行消耗
     */
    private static void thenAcceptBoth()  {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 3 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future1結果:{}",t);
            return t;
        } );

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 3 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future2結果:{}",t);
            return t;
        } );

        future1.thenAcceptBoth( future2, (integer, integer2) -> log.info("thenAcceptBoth:當兩個任務都執行完後彙總," +
                " future1結果:{},future2的結果:{}",integer,integer2) );
    }

    /***
     * 兩個CompletionStage,誰執行返回的結果快,就用那個CompletionStage的結果進行下一步的轉化操作。
     */
    private static void applyToEither()  {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 4 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future1結果:{}",t);
            return t;
        } );
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 4 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future2結果:{}",t);
            return t;
        } );

        CompletableFuture<Integer> result = future1.applyToEither( future2, t -> {
            log.info("applyToEither接收到第一個完成任務的結果是:{}",t);
            return t * 2;
        } );
        log.info( "applyToEither最終結果是:{}",result );
    }

    /***
     * 兩個CompletionStage,誰執行返回的結果快,我就用那個CompletionStage的結果進行下一步的消耗操作。
     */
    private static void acceptEither() {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 5 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future1結果:{}",t);
            return t;
        } );

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 5 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future2結果:{}",t);
            return t;
        } );
        future1.acceptEither( future2, t -> log.info("acceptEither接收到第一個完成任務的結果是:{}",t) );
    }

    /***
     * 兩個CompletionStage,任何一個完成了都會執行下一步的操作
     */
    private static void runAfterEither() {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 2 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future1結果:{}",t);
            return t;
        } );

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync( () -> {
            int t = new Random().nextInt( 2 );
            try {
                TimeUnit.SECONDS.sleep( t );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future2結果:{}",t);
            return t;
        } );
        future1.runAfterEither( future2, () -> log.info("只要有一個任務執行結束,我就會被執行到") );
    }

    /***
     * 兩個CompletionStage,都完成了計算纔會執行下一步的操作
     */
    private static void runAfterBoth() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> fu1 = CompletableFuture.supplyAsync( () -> {
            int time = new Random().nextInt( 3 );
            try {
                TimeUnit.SECONDS.sleep( time+1 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future1結果:{}",time);
            return time;
        } );

        CompletableFuture<Integer> fu2 = CompletableFuture.supplyAsync( () -> {
            int time = new Random().nextInt( 3 );
            try {
                TimeUnit.SECONDS.sleep( time+1 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("future2結果:{}",time);
            return time;
        } );
        fu1.get();
        fu2.get();
        fu1.runAfterBoth( fu2, () -> log.info("當兩個任務都執行結束,我就會被執行到") );
    }

    /***
     * thenCompose 方法允許你對兩個 CompletionStage 進行流水線操作,第一個操作完成時,將其結果作爲參數傳遞給第二個操作。
     */
    private static void thenCompose() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync( () -> {
            int r = new Random().nextInt( 5 );
            log.info("future1結果:{}",r);
            return r;
        } ).thenCompose( param -> CompletableFuture.supplyAsync( () -> {
            int r = param * 10;
            log.info("thenCompose執行結果:{}",r);
            return r;
        } ) );
        log.info("thenCompose執行結果:{}",future.get());

    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        runAsync();
        supplyAsync();
        whenComplete();
        thenApply();
        handle();
        thenAccept();
        thenRun();
        thenCombine();
        thenAcceptBoth();
        applyToEither();
        acceptEither();
        runAfterEither();
        runAfterBoth();
        thenCompose();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章