1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

CompletionService
可自行实现该接口.这是一个任务队列.
取出队列元素的poll和take方法
take会阻塞知道队列出现结果
poll使用的前提是确保队列已经有结果,不然贸贸然使用会出现空指针.可以指定一个超时等待时间,避免长时间卡死.
ExecutorCompletionService
一般都是声明CompletionService<V>,实例化ExecutorCompletionService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int TOTAL_TASK = 2;
public void run() throws InterruptedException, ExecutionException {
// 创建线程池
ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);
// 向里面扔任务
for (int i = 0; i < TOTAL_TASK; i++) {
cService.submit(new CallableExample());
//重载的这个submit(Runnable task, V result)方法,是自行把结果传入
}
// 检查线程池任务执行结果
for (int i = 0; i < TOTAL_TASK; i++) {
Future<Integer> future = cService.take();
System.out.println("method:" + future.get());
}
// 关闭线程池
pool.shutdown();
}
1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

CompletionService
You can implement this interface yourself. This is a task queue.
poll and take methods for retrieving queue elements.
take will block until a result appears in the queue.
poll should be used on the premise that the queue already has results, otherwise using it rashly will cause null pointer. You can specify a timeout wait time to avoid long blocking.
ExecutorCompletionService
Generally declare CompletionService<V>, instantiate ExecutorCompletionService.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int TOTAL_TASK = 2;
public void run() throws InterruptedException, ExecutionException {
// Create thread pool
ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);
// Throw tasks into it
for (int i = 0; i < TOTAL_TASK; i++) {
cService.submit(new CallableExample());
//This overloaded submit(Runnable task, V result) method passes the result in yourself
}
// Check thread pool task execution results
for (int i = 0; i < TOTAL_TASK; i++) {
Future<Integer> future = cService.take();
System.out.println("method:" + future.get());
}
// Shutdown thread pool
pool.shutdown();
}
1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

CompletionService
このインターフェースを自分で実装できます。これはタスクキューです。
キュー要素を取得するpollメソッドとtakeメソッド。
takeはキューに結果が現れるまでブロックします。
pollは、キューにすでに結果があることを前提に使用する必要があります。そうでない場合、軽率に使用するとnullポインターが発生します。長時間のブロックを避けるために、タイムアウト待機時間を指定できます。
ExecutorCompletionService
一般的にCompletionService<V>を宣言し、ExecutorCompletionServiceをインスタンス化します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int TOTAL_TASK = 2;
public void run() throws InterruptedException, ExecutionException {
// スレッドプールを作成
ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);
// タスクを投入
for (int i = 0; i < TOTAL_TASK; i++) {
cService.submit(new CallableExample());
//このオーバーロードされたsubmit(Runnable task, V result)メソッドは、結果を自分で渡します
}
// スレッドプールタスクの実行結果を確認
for (int i = 0; i < TOTAL_TASK; i++) {
Future<Integer> future = cService.take();
System.out.println("method:" + future.get());
}
// スレッドプールをシャットダウン
pool.shutdown();
}
1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

CompletionService
Вы можете реализовать этот интерфейс самостоятельно. Это очередь задач.
Методы poll и take для извлечения элементов очереди.
take будет блокировать до появления результата в очереди.
poll следует использовать при условии, что очередь уже имеет результаты, иначе опрометчивое использование вызовет нулевой указатель. Вы можете указать время ожидания таймаута, чтобы избежать длительной блокировки.
ExecutorCompletionService
Обычно объявляют CompletionService<V>, создают экземпляр ExecutorCompletionService.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int TOTAL_TASK = 2;
public void run() throws InterruptedException, ExecutionException {
// Создать пул потоков
ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);
// Бросить задачи в него
for (int i = 0; i < TOTAL_TASK; i++) {
cService.submit(new CallableExample());
//Этот перегруженный метод submit(Runnable task, V result) передает результат сам
}
// Проверить результаты выполнения задач пула потоков
for (int i = 0; i < TOTAL_TASK; i++) {
Future<Integer> future = cService.take();
System.out.println("method:" + future.get());
}
// Завершить работу пула потоков
pool.shutdown();
}
💬 讨论 / Discussion
对这篇文章有想法?欢迎在 GitHub 上发起讨论。
Have thoughts on this post? Start a discussion on GitHub.