JDK 8 다 중 스 레 드 JUC 의 Complete bleFuture 사용

69619 단어 자바
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();
    }
}

좋은 웹페이지 즐겨찾기