我正在使用init()进行同步。但是我必须在init()中运行一些指令,该指令必须在主线程上执行。因此,我创建了一个runnable来添加此指令。这些指令有一些异步调用。
因此,我正在探索有效的方法来阻止init(),直到所有指令均成功完成。
Static void init() {
new Handler(context.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// doing some async calls
}
}
}
答案 0 :(得分:0)
您需要同步init()
方法,然后使用CompletionService
等待Future
完成。像这样:
public synchronized void init() throws InterruptedException {
Executor executor = Executors.newFixedThreadPool(4);
CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
// 4 tasks
for (int i = 0; i < 4; i++) {
completionService.submit(new Callable<String>() {
public String call() {
return "i am an async task finished";
}
});
}
int received = 0;
boolean errors = false;
while (received < 4 && !errors) {
Future<String> resultFuture = completionService.take(); // blocks if none available
try {
String result = resultFuture.get();
System.out.println(result);
received++;
} catch (Exception e) {
errors = true;
/// some acceptable error handling;
}
}
}
我从this thread那里获取了代码,并根据您的需要采用了它。不要忘记像描述的here那样正确处理InterruptedException
。