Future

public interface Runnable {
    void run();
}
public interface Callable<V> {
    V call() throws Exception;// 区别仅在于有返回值
}
Future代表了一个异步计算的结果
提供了一些方法:检查计算是否完成, 取消任务, 是否被取消, 取得计算结果等等
// A Future represents the result of an asynchronous computation.
// Methods are provided to check if the computation is complete, to wait for its completion
// and to retrieve the result of the computation.
计算结果只能通过get方法取得,如果计算没有完成get会陷入阻塞
// The result can only be retrieved using method {@code get} when the computation
// has completed, blocking if necessary until it is ready.
public interface Future<V>
public interface RunnableFuture<V> extends Runnable, Future<V>

// A cancellable asynchronous computation.
FutureTask类是Future接口的一个基本实现,实现了相关方法
// This class provides a base implementation of {@link Future}
// The result can only be retrieved when the computation has completed;
// the {@code get} methods will block if the computation has not yet completed.
FutureTask可以被用来去包装一个Callable或者Runnable
// A {@code FutureTask} can be used to wrap a {@link Callable} or {@link Runnable} object.
public class FutureTask<V> implements RunnableFuture<V>
// Thread构造
Thread()
Thread(Runnable target) // 可以直接传一个FutureTask对象
Thread(Runnable target, String name)
// 返回结果是Integer
FutureTask<Integer> fu = new FutureTask<>(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        log.debug("========");
        return 100;
    }
});
new Thread(fu,"t").start();
System.out.println(fu.get()); // 100

get是阻塞获取,子线程还没执行完的话,会阻塞等待
get还有一个重载的,如果指定时间内没拿到数据,会抛TimeoutException

CompletableFuture

static CompletableFuture<Void> runAsync(Runnable runnable)
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
ExecutorService pool = Executors.newFixedThreadPool(3);

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
    System.out.println(Thread.currentThread().getName());
    System.out.println(Thread.currentThread().isDaemon());
    try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
    return "sbs";
},pool); // 不传线程池的话,默认用的ForkJoin线程池(守护线程)

System.out.println(cf.get()); // 也是阻塞式获取
System.out.println("==========");

常用方法

// 下面个方法都是上一stage正常完成,才会触发调用
// Returns a new CompletionStage that, when this stage completes normally
// 当上一stage正常完成时,fn被调用, 处理转换(上一stage的结果)
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
// 当上一stage正常完成时,action被调用, 消费(上一stage的结果)
CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 当上一stage正常完成时,action被调用
CompletionStage<Void> thenRun(Runnable action);
// 可以和thenApply进行对比,返回的CompletionStage就是fn返回的那个
<U> CompletionStage<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
// 当上一stage和other两个都正常完成时, fn被调用
<U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);


// 无论上一stage completed normally or exceptionally, whenComplete和handle都会被触发调用
// whenComplete返回的stage,result还是上一stage的result
// handle处理上一stage的result,返回新的result

// Returns a new CompletionStage with the same result or exception as this stage
// 返回的stage的(result或exception)和上一个stage一样,参数是消费型接口(上一stage的结果, 上一stage的异常)
// 上一stage正常完成,但是action抛出了异常,则返回的新stage异常完成(异常是action抛出的异常)
// 上一stage异常完成,且action也抛出了异常,则返回的新stage异常完成(异常是上一stage抛出的异常)
CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
<U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
ExecutorService pool = Executors.newFixedThreadPool(3);
CompletableFuture<Integer> lp = CompletableFuture.runAsync(() -> {
    log.debug("{}",Thread.currentThread().getClass());
    //int i = 1 / 0;        // 上一阶段正常完成才会触发thenApply
},pool).thenApply(res -> { // 上一阶段出现异常,thenApply不会被触发
    log.debug("{}", res); // res是上一阶段返回的结果
    return 12;
});
//log.debug("{}",lp.get()); // 12

get和join的区别
get抛的是编译时异常,需要立即处理
join抛的是运行时异常,不需要处理也可以
暂时先写这些吧,CompletableFuture用到再说

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值