CompletableFuture - Hello World

原创转载请注明出处:http://agilestyle.iteye.com/blog/2427053

 

completableFuture.get()

package org.fool.java8.completable;

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

public class CompletableFutureTest0 {

    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Double> completableFuture = new CompletableFuture<>();

        new Thread(() -> {
            double result = get();
            completableFuture.complete(result);
        }).start();

        System.out.println("=========main start no block==========");

        Optional.ofNullable(completableFuture.get()).ifPresent(System.out::println);

        System.out.println("=========main end no block==========");
    }

    private static double get() {
        try {
            Thread.sleep(RANDOM.nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return RANDOM.nextDouble();
    }
}

Console Output

Note:  completableFuture.get()  是阻塞的

 

CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action)

package org.fool.java8.completable;

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

public class CompletableFutureTest1 {

    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Double> completableFuture = new CompletableFuture<>();

        new Thread(() -> {
            double result = get();
            completableFuture.complete(result);
        }).start();

        System.out.println("=========main start no block==========");

        completableFuture.whenComplete((v, t) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(t).ifPresent(Throwable::printStackTrace);
        });

        System.out.println("=========main end no block==========");
    }

    private static double get() {
        try {
            Thread.sleep(RANDOM.nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return RANDOM.nextDouble();
    }
}

Console Output


Note: completableFuture.whenComplete  是非阻塞的 

 

<U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

package org.fool.java8.completable;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;

public class CompletableFutureTest2 {

    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        AtomicBoolean finished = new AtomicBoolean(false);

        CompletableFuture.supplyAsync(CompletableFutureTest2::get).whenComplete((v, t) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(t).ifPresent(Throwable::printStackTrace);

            finished.set(true);
        });

        System.out.println("===========main start no block============");

        while (!finished.get()) {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
        }

        System.out.println("=========main end no block==========");
    }

    private static double get() {
        try {
            Thread.sleep(RANDOM.nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return RANDOM.nextDouble();
    }
}

Console Output


 当把while那段代码注释掉


 再次执行


Note:  这个方法启动的是一个daemon线程


 

<U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

package org.fool.java8.completable;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class CompletableFutureTest3 {

    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        AtomicBoolean finished = new AtomicBoolean(false);

        ExecutorService executorService = Executors.newFixedThreadPool(2, r -> {
            Thread t = new Thread(r);
            t.setDaemon(false);
            return t;
        });

        CompletableFuture.supplyAsync(CompletableFutureTest3::get, executorService).whenComplete((v, t) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(t).ifPresent(Throwable::printStackTrace);

            finished.set(true);
        });

        System.out.println("===========main start no block============");

        while (!finished.get()) {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
        }

        System.out.println("=========main end no block==========");
    }

    private static double get() {
        try {
            Thread.sleep(RANDOM.nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return RANDOM.nextDouble();
    }
}

Console Output


Note:  使用ExecutorService默认线程是非Daemon线程,这里将线程显示设置为非Daemon线程,运行完毕,程序还是处于hold状态


 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值