如何检查@Async 调用是否在 Spring 内完成?
How to check that @Async call completed in Spring?
我正在对执行 rsync 命令的方法使用 @Async 注释。一次有 10 个线程 调用此方法。我的要求是在所有十个线程完成 rsync 命令执行之后,只有我剩下的代码应该执行但不知道如何检查我的所有十个线程是否已完全执行 @Async 方法?所以请告诉我一种检查方法
如果您要 return 一些值,您应该将 return 值包装到标准 Java SE Future
或 Spring 的 AsyncResult
,它也实现了 Future
。
像这样:
@Component
class AsyncTask {
@Async
public Future<String> call() throws InterruptedException {
return new AsyncResult<String>("return value");
}
}
如果你确实有这个,在来电者你做这样的事情:
public void kickOffAsyncTask() throws InterruptedException {
Future<String> futureResult = asyncTask.call();
//do some stuff in parallel
String result = futureResult.get();
System.out.println(result);
}
调用 futureResult.get()
将阻塞调用线程并等待异步线程完成。
如果您不想永远等待,可以选择使用 Future.get(long timeout, TimeUnit unit)
。
编辑:
如果您不需要 return 任何值,我仍然建议考虑 returning 虚拟 return 值。您不需要将它用于任何事情,只需用于指示特定线程已完成。像这样:
public void kickOffAsyncTasks(int execCount) throws InterruptedException {
Collection<Future<String>> results = new ArrayList<>(execCount);
//kick off all threads
for (int idx = 0; idx < execCount; idx++) {
results.add(asyncTask.call());
}
// wait for all threads
results.forEach(result -> {
try {
result.get();
} catch (InterruptedException | ExecutionException e) {
//handle thread error
}
});
//all threads finished
}
我正在对执行 rsync 命令的方法使用 @Async 注释。一次有 10 个线程 调用此方法。我的要求是在所有十个线程完成 rsync 命令执行之后,只有我剩下的代码应该执行但不知道如何检查我的所有十个线程是否已完全执行 @Async 方法?所以请告诉我一种检查方法
如果您要 return 一些值,您应该将 return 值包装到标准 Java SE Future
或 Spring 的 AsyncResult
,它也实现了 Future
。
像这样:
@Component
class AsyncTask {
@Async
public Future<String> call() throws InterruptedException {
return new AsyncResult<String>("return value");
}
}
如果你确实有这个,在来电者你做这样的事情:
public void kickOffAsyncTask() throws InterruptedException {
Future<String> futureResult = asyncTask.call();
//do some stuff in parallel
String result = futureResult.get();
System.out.println(result);
}
调用 futureResult.get()
将阻塞调用线程并等待异步线程完成。
如果您不想永远等待,可以选择使用 Future.get(long timeout, TimeUnit unit)
。
编辑:
如果您不需要 return 任何值,我仍然建议考虑 returning 虚拟 return 值。您不需要将它用于任何事情,只需用于指示特定线程已完成。像这样:
public void kickOffAsyncTasks(int execCount) throws InterruptedException {
Collection<Future<String>> results = new ArrayList<>(execCount);
//kick off all threads
for (int idx = 0; idx < execCount; idx++) {
results.add(asyncTask.call());
}
// wait for all threads
results.forEach(result -> {
try {
result.get();
} catch (InterruptedException | ExecutionException e) {
//handle thread error
}
});
//all threads finished
}