Executor

Executor

Executors abstract from thread creation:
从新建线程中抽象出来的,可以是创建线程,也可以是重复使用线程。
void execute(Runnable runnable)

ExecutorService

另一个interface, 他有lifecycle management logic
在这里插入图片描述
用一个线程构建一个Executor,以及构建一个线程库的方法。
life management logic:
在这里插入图片描述
一个装着tasks的list,直到他们停下来才不去执行
不会停止知道shutdown()

线程的返回值

在这里插入图片描述
其中call()可以返回结果

Future: Representation of Results

Future 表示了一些未来“计算”的结果,他们是不同步的产生 并存放在future中
这些“计算”可以被取消也可以未完成
结果只能完成计算才能获得
Future submit(Callable callable)
在这里插入图片描述
submit()返回future

Futures: Retrieving Results

The result of the Callable can be retrieved from the Future using its
get() method
在这里插入图片描述

Future: waiting for the results

在这里插入图片描述
isDone(): Returns whether the task finished
get(int timeout, TimeUnit unit): 允许去等timeout的时间

ScheduledExecutorService

更是一种对与时间的安排
A subinterface of ExecutorService
Supports scheduled execution of tasks
在这里插入图片描述
This example schedules a task after a delay of three seconds:
在这里插入图片描述

CompletableFutures

这个call只能查询一个结果 但不能"registering a callback" : 让其他线程在未来也可以调用。
其实也就是说,它可以让你做一连串任务,比如你先做X, 你还需要做Y 用到X的结果,你就可以一直这么做。
在这里插入图片描述On a CompletableFuture, the thenApply method can be called to define behavior that is executed after the task has finished
thenApply()就是结束任务之后的行为

/**
* A supplier that sleeps for a second, and then returns one
**/
public static class MySupplier implements Supplier<Integer> {

    @Override
    public Integer get() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //Do nothing
        }
        return 1;
    }
}

/**
* A (pure) function that adds one to a given Integer
**/
public static class PlusOne implements Function<Integer, Integer> {

    @Override
    public Integer apply(Integer x) {
        return x + 1;
    }
}

public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec);
    System.out.println(f.isDone()); // False
    CompletableFuture<Integer> f2 = f.thenApply(new PlusOne());
    System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值