Callable 为 运行 时的异步回调
Asynch callback while Callable is running
假设我有一个 Person 对象:
public class Person {
private String name;
private History history;
}
历史记录需要很长时间才能生成,所以我创建了一个
实现 Callable 的 HistoryCallable class,以异步生成历史记录:
public class HistoryCallable implements Callable<HistoryResult> {
@Override
public HistoryResult call() {
// do a lot of stuff
}
现在假设我有一个人物列表,我想为每个人生成历史记录。我创建了一个 HistoryCallable 列表,并将每个列表提交给一个 ExecutorService:
ExecutorService execService = Executors.newFixedThreadPool();
List<Future<HistoryResult>> results = new ArrayList<>();
for (final Callable<HistoryResult> historyCallable : historyCallables) {
final Future<HistoryResult> future = execService.submit(historyCallable);
results.add(mixingThread);
}
我的问题是:这些 HistoryCallable 实例对它们所属的 Person 一无所知。然而,由于它们需要很长时间才能完成,我需要知道每个人的进展情况、所处的阶段等。
无论如何我可以使用回调(或其他东西),not 当每个 Callable 完成时,而是当每个 Callable 完成时是 运行,让我知道每个人的进度,而不向每个 Callable 传递任何个人信息?
这样的事情怎么样:
public class HistoryCallable implements Callable<HistoryResult> {
private long totalItems;
private volatile long itemsProcessed;
@Override
public HistoryResult call() {
// do a lot of stuff
// after each item:
itemsProcessed++;
}
public long getItemsProcessed() {
return itemsProcessed;
}
public long getTotalItems() {
return totalItems;
}
}
public class PersonHistoryBuilder {
private Person person;
private HistoryCallable callable;
public Person getPerson() {
return person;
}
public float getProgressPercent() {
return (100.0f * callable.getItemsProcessed()) / callable.getTotalItems();
}
}
假设我有一个 Person 对象:
public class Person {
private String name;
private History history;
}
历史记录需要很长时间才能生成,所以我创建了一个 实现 Callable 的 HistoryCallable class,以异步生成历史记录:
public class HistoryCallable implements Callable<HistoryResult> {
@Override
public HistoryResult call() {
// do a lot of stuff
}
现在假设我有一个人物列表,我想为每个人生成历史记录。我创建了一个 HistoryCallable 列表,并将每个列表提交给一个 ExecutorService:
ExecutorService execService = Executors.newFixedThreadPool();
List<Future<HistoryResult>> results = new ArrayList<>();
for (final Callable<HistoryResult> historyCallable : historyCallables) {
final Future<HistoryResult> future = execService.submit(historyCallable);
results.add(mixingThread);
}
我的问题是:这些 HistoryCallable 实例对它们所属的 Person 一无所知。然而,由于它们需要很长时间才能完成,我需要知道每个人的进展情况、所处的阶段等。
无论如何我可以使用回调(或其他东西),not 当每个 Callable 完成时,而是当每个 Callable 完成时是 运行,让我知道每个人的进度,而不向每个 Callable 传递任何个人信息?
这样的事情怎么样:
public class HistoryCallable implements Callable<HistoryResult> {
private long totalItems;
private volatile long itemsProcessed;
@Override
public HistoryResult call() {
// do a lot of stuff
// after each item:
itemsProcessed++;
}
public long getItemsProcessed() {
return itemsProcessed;
}
public long getTotalItems() {
return totalItems;
}
}
public class PersonHistoryBuilder {
private Person person;
private HistoryCallable callable;
public Person getPerson() {
return person;
}
public float getProgressPercent() {
return (100.0f * callable.getItemsProcessed()) / callable.getTotalItems();
}
}