DnA*_*DnA 10 java spring asynchronous spring-mvc
我使用@Async注释执行rsync命令的方法.一次有十个线程调用此方法.我的要求是在所有十个线程完成rsync命令执行之后,只有我剩下的代码应该执行但是没有得到如何检查我的所有十个线程是否完全执行了@Async方法?所以请告诉我一个方法来检查它
lub*_*nac 26
如果要返回一些值,则应将返回值包装到标准Java SE Future或Spring中AsyncResult,这Future也是实现的.
像这样的东西:
@Component
class AsyncTask {
@Async
public Future<String> call() throws InterruptedException {
return new AsyncResult<String>("return value");
}
}
Run Code Online (Sandbox Code Playgroud)
如果你确实有这个,在调用者你做的事情如下:
public void kickOffAsyncTask() throws InterruptedException {
Future<String> futureResult = asyncTask.call();
//do some stuff in parallel
String result = futureResult.get();
System.out.println(result);
}
Run Code Online (Sandbox Code Playgroud)
调用futureResult.get()将阻止调用程序线程并等待异步线程完成.
Future.get(long timeout, TimeUnit unit)如果您不想永远等待,可以选择使用.
编辑:
如果您不需要返回任何值,我仍然建议考虑返回虚拟返回值.您不需要将它用于任何事情,只需用于指示特定线程已完成.像这样的东西:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19575 次 |
| 最近记录: |