jdk8的async实现

https://www.jianshu.com/p/547d2d7761db

 

package com.zxg;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class comFuture {
    public static void main(String[] args) throws Exception {
        {
            ExecutorService executor = Executors.newFixedThreadPool(4);

            Future future = executor.submit(() -> {
                Thread.sleep(2000);
                return "hello world";
            });
//轮询获取结果
            while (true) {
                if (future.isDone()) {
                    System.out.println(future.get());
                    break;
                }
            }
            executor.shutdown();
        }

        {
            System.err.println("async");
            ExecutorService executor = Executors.newFixedThreadPool(4);


            CompletableFuture future = CompletableFuture.supplyAsync(() -> {
                return "hello world";
            }, executor);

            future.complete("goAway");


            //thenapply可以在后面拼东西
            future = future.thenApply((element)->{
                return element+"  addPart";
            }).thenApply((element)->{
                return element+"  addTwoPart";
            });
            //等到有值了再获取
            //System.out.println(future.get());

            future.whenComplete((v, e) -> {
                System.out.println("return value:" + v + "  exception:" + e);
            });

            //除了这个whenComplete还有一个方法叫handle , 不同的就是他返回一个返回值,而

            executor.shutdown();
        }

    }
}

你可能感兴趣的:(jdk8的async实现)