1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
graph TB
g(Comparable<Delayed>)-->A
A(Delayed)-->C(ScheduledFuture<V>)
D(Runnable)-->e(RunnableFuture<V>)
F(Future<V>)-->e(RunnableFuture<V>)
F-->C
e-->B(RunnableScheduledFuture<V>)
C-->B
cs(CompletionStage<T>)-->cf(CompletableFuture<T>)
F-->cf
F-->cc(CountedCompleter<T>)
e-->ft(FutureTask)
F-->fjt(ForkJoinTask<V>)
fjt-->cct(CountedCompleter<T>)
fjt-->rsa(RecursiveAction)
fjt-->rtt(RecursiveTask<V>)

Future
上图可以看出Future<V>地位超凡,基本上很多成员都是他”儿子”
Future
ScheduledFuture
代表了一种预期的任务,比如可以用ScheduledFuture配合ScheduledExecutorService来做一个周期性的重复作业(scheduleAtFixedRate),延迟作业(scheduleWithFixedDelay)
RunnableScheduledFuture
这是个接口,得自己实现。
可用于一次性任务或者周期性任务。
这里可以参考他的子接口.ScheduledFuture的用法
RunnableFuture
这是个接口,得自己实现。
FutureTask
可用Callable<V>和Runnable初始化。Callable<V>带返回值。
可配合ExecutorService实现多线程任务分发
CompletableFuture
可以用来创建链式服务(1启动多任务)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int i = 1;
public void run() throws InterruptedException, ExecutionException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
i = i << 1;
return "end 1";
});
future.thenApply((s) -> {
//把上个任务的结果传递到子任务中
out.println(s);
out.println("end 2");
i = i << 1;
return "hhh";
});
future.thenRun(() -> {
try {
Thread.sleep(1000);
i = i << 1;
} catch (InterruptedException e) {
}
out.println("CompletableFutureExample end");
});
//通过这个信号,持续等待子线程运行完毕
while (i != 8) {
Thread.sleep(500);
out.println("继续等待");
}
// future.join();
// CompletableFuture.allOf(future).join();
}
CountedCompleter
CountedCompleter:任务可能产生结果,也可能不产生结果。
CountedCompleter 在任务完成执行后会触发执行一个自定义的钩子函数。
RecursiveAction
跟CountedCompleter
RecursiveTask
RecursiveTask类的实例表示产生结果的任务。
特点在于可递归执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RecursiveTaskExample extends RecursiveTask<Integer> {
final int n;
RecursiveTaskExample(int n) {
this.n = n;
}
/**
* The main computation performed by this task.
*
* @return the result of the computation
*/
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
RecursiveTaskExample f1 = new RecursiveTaskExample(n - 1);
f1.fork();
RecursiveTaskExample f2 = new RecursiveTaskExample(n - 2);
return f2.compute() + f1.join();
}
}
参考链接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
graph TB
g(Comparable<Delayed>)-->A
A(Delayed)-->C(ScheduledFuture<V>)
D(Runnable)-->e(RunnableFuture<V>)
F(Future<V>)-->e(RunnableFuture<V>)
F-->C
e-->B(RunnableScheduledFuture<V>)
C-->B
cs(CompletionStage<T>)-->cf(CompletableFuture<T>)
F-->cf
F-->cc(CountedCompleter<T>)
e-->ft(FutureTask)
F-->fjt(ForkJoinTask<V>)
fjt-->cct(CountedCompleter<T>)
fjt-->rsa(RecursiveAction)
fjt-->rtt(RecursiveTask<V>)

Future
From the diagram above, we can see that Future<V> has an extraordinary status, basically many members are its “children”.
Future
ScheduledFuture
Represents a scheduled task. For example, ScheduledFuture can be used with ScheduledExecutorService to do periodic repeated jobs (scheduleAtFixedRate), delayed jobs (scheduleWithFixedDelay).
RunnableScheduledFuture
This is an interface, you need to implement it yourself.
Can be used for one-time tasks or periodic tasks.
You can refer to its sub-interface here. Usage of ScheduledFuture.
RunnableFuture
This is an interface, you need to implement it yourself.
FutureTask
Can be initialized with Callable<V> and Runnable. Callable<V> has a return value.
Can be used with ExecutorService to implement multi-threaded task distribution.
CompletableFuture
Can be used to create chained services (1 starts multiple tasks).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int i = 1;
public void run() throws InterruptedException, ExecutionException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
i = i << 1;
return "end 1";
});
future.thenApply((s) -> {
// Pass the result of the previous task to the child task
out.println(s);
out.println("end 2");
i = i << 1;
return "hhh";
});
future.thenRun(() -> {
try {
Thread.sleep(1000);
i = i << 1;
} catch (InterruptedException e) {
}
out.println("CompletableFutureExample end");
});
// Through this signal, continuously wait for child threads to finish running
while (i != 8) {
Thread.sleep(500);
out.println("Continue waiting");
}
// future.join();
// CompletableFuture.allOf(future).join();
}
CountedCompleter
CountedCompleter: Tasks may produce results, or may not produce results.
CountedCompleter will trigger execution of a custom hook function after the task completes execution.
RecursiveAction
Like CountedCompleter
RecursiveTask
Instances of the RecursiveTask class represent tasks that produce results.
The characteristic is that it can be executed recursively.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RecursiveTaskExample extends RecursiveTask<Integer> {
final int n;
RecursiveTaskExample(int n) {
this.n = n;
}
/**
* The main computation performed by this task.
*
* @return the result of the computation
*/
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
RecursiveTaskExample f1 = new RecursiveTaskExample(n - 1);
f1.fork();
RecursiveTaskExample f2 = new RecursiveTaskExample(n - 2);
return f2.compute() + f1.join();
}
}
Reference links:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
graph TB
g(Comparable<Delayed>)-->A
A(Delayed)-->C(ScheduledFuture<V>)
D(Runnable)-->e(RunnableFuture<V>)
F(Future<V>)-->e(RunnableFuture<V>)
F-->C
e-->B(RunnableScheduledFuture<V>)
C-->B
cs(CompletionStage<T>)-->cf(CompletableFuture<T>)
F-->cf
F-->cc(CountedCompleter<T>)
e-->ft(FutureTask)
F-->fjt(ForkJoinTask<V>)
fjt-->cct(CountedCompleter<T>)
fjt-->rsa(RecursiveAction)
fjt-->rtt(RecursiveTask<V>)

Future
上の図から、Future<V>が並外れた地位を持っていることがわかります。基本的に多くのメンバーがその「子」です。
Future
ScheduledFuture
予定されたタスクを表します。たとえば、ScheduledFutureをScheduledExecutorServiceと組み合わせて、周期的な繰り返し作業(scheduleAtFixedRate)、遅延作業(scheduleWithFixedDelay)を行うことができます。
RunnableScheduledFuture
これはインターフェースで、自分で実装する必要があります。
1回限りのタスクまたは周期的なタスクに使用できます。
ここでそのサブインターフェースを参照できます。ScheduledFutureの用法。
RunnableFuture
これはインターフェースで、自分で実装する必要があります。
FutureTask
Callable<V>とRunnableで初期化できます。Callable<V>には戻り値があります。
ExecutorServiceと組み合わせて、マルチスレッドタスク分散を実装できます。
CompletableFuture
チェーンサービス(1が複数のタスクを開始)を作成するために使用できます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int i = 1;
public void run() throws InterruptedException, ExecutionException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
i = i << 1;
return "end 1";
});
future.thenApply((s) -> {
// 前のタスクの結果を子タスクに渡す
out.println(s);
out.println("end 2");
i = i << 1;
return "hhh";
});
future.thenRun(() -> {
try {
Thread.sleep(1000);
i = i << 1;
} catch (InterruptedException e) {
}
out.println("CompletableFutureExample end");
});
// この信号を通じて、子スレッドの実行完了を継続的に待機
while (i != 8) {
Thread.sleep(500);
out.println("継続的に待機");
}
// future.join();
// CompletableFuture.allOf(future).join();
}
CountedCompleter
CountedCompleter:タスクは結果を生成する場合と生成しない場合があります。
CountedCompleterは、タスクの実行完了後にカスタムフック関数の実行をトリガーします。
RecursiveAction
CountedCompleter
RecursiveTask
RecursiveTaskクラスのインスタンスは、結果を生成するタスクを表します。
特徴は、再帰的に実行できることです。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RecursiveTaskExample extends RecursiveTask<Integer> {
final int n;
RecursiveTaskExample(int n) {
this.n = n;
}
/**
* The main computation performed by this task.
*
* @return the result of the computation
*/
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
RecursiveTaskExample f1 = new RecursiveTaskExample(n - 1);
f1.fork();
RecursiveTaskExample f2 = new RecursiveTaskExample(n - 2);
return f2.compute() + f1.join();
}
}
参考リンク:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
graph TB
g(Comparable<Delayed>)-->A
A(Delayed)-->C(ScheduledFuture<V>)
D(Runnable)-->e(RunnableFuture<V>)
F(Future<V>)-->e(RunnableFuture<V>)
F-->C
e-->B(RunnableScheduledFuture<V>)
C-->B
cs(CompletionStage<T>)-->cf(CompletableFuture<T>)
F-->cf
F-->cc(CountedCompleter<T>)
e-->ft(FutureTask)
F-->fjt(ForkJoinTask<V>)
fjt-->cct(CountedCompleter<T>)
fjt-->rsa(RecursiveAction)
fjt-->rtt(RecursiveTask<V>)

Future
Из диаграммы выше видно, что Future<V> имеет исключительный статус, в основном многие члены являются его “детьми”.
Future
ScheduledFuture
Представляет запланированную задачу. Например, ScheduledFuture можно использовать с ScheduledExecutorService для выполнения периодических повторяющихся задач (scheduleAtFixedRate), отложенных задач (scheduleWithFixedDelay).
RunnableScheduledFuture
Это интерфейс, вам нужно реализовать его самостоятельно.
Может использоваться для одноразовых задач или периодических задач.
Здесь вы можете обратиться к его подынтерфейсу. Использование ScheduledFuture.
RunnableFuture
Это интерфейс, вам нужно реализовать его самостоятельно.
FutureTask
Может быть инициализирован с Callable<V> и Runnable. Callable<V> имеет возвращаемое значение.
Может использоваться с ExecutorService для реализации распределения многопоточных задач.
CompletableFuture
Может использоваться для создания цепочечных сервисов (1 запускает несколько задач).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int i = 1;
public void run() throws InterruptedException, ExecutionException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
i = i << 1;
return "end 1";
});
future.thenApply((s) -> {
// Передать результат предыдущей задачи в дочернюю задачу
out.println(s);
out.println("end 2");
i = i << 1;
return "hhh";
});
future.thenRun(() -> {
try {
Thread.sleep(1000);
i = i << 1;
} catch (InterruptedException e) {
}
out.println("CompletableFutureExample end");
});
// Через этот сигнал, непрерывно ждать завершения выполнения дочерних потоков
while (i != 8) {
Thread.sleep(500);
out.println("Продолжать ждать");
}
// future.join();
// CompletableFuture.allOf(future).join();
}
CountedCompleter
CountedCompleter: Задачи могут производить результаты или могут не производить результаты.
CountedCompleter запустит выполнение пользовательской функции-хука после завершения выполнения задачи.
RecursiveAction
Как CountedCompleter
RecursiveTask
Экземпляры класса RecursiveTask представляют задачи, которые производят результаты.
Характеристика в том, что он может выполняться рекурсивно.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RecursiveTaskExample extends RecursiveTask<Integer> {
final int n;
RecursiveTaskExample(int n) {
this.n = n;
}
/**
* The main computation performed by this task.
*
* @return the result of the computation
*/
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
RecursiveTaskExample f1 = new RecursiveTaskExample(n - 1);
f1.fork();
RecursiveTaskExample f2 = new RecursiveTaskExample(n - 2);
return f2.compute() + f1.join();
}
}
Ссылки:
💬 讨论 / Discussion
对这篇文章有想法?欢迎在 GitHub 上发起讨论。
Have thoughts on this post? Start a discussion on GitHub.