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
}