如何等到所有线程完成执行? [英] How to wait until all threads complete their execution?
问题描述
假设我正在使用 HTTP 请求库来下载文件.该库在内部使用线程.现在,我想等待主线程,直到其他线程完成它们的执行.
Say I'm using a HTTP requests library for downloading files. This library uses threads inside. Now, I want to wait on the main thread until other threads complete their execution.
我通过谷歌搜索找到的所有其他解决方案只有在我有权访问库中使用的线程变量时才有效.但我无法访问这些.
All the other solutions that I found by googling only work if I have access to the Thread variables that were used in the library. But these are not accessible to me.
这是我目前使用的:
package smartzero.eightnoteight.testfirebase;
import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("email: ");
String email = in.nextLine();
System.out.print("password: ");
String password = in.nextLine();
Firebase fb = new Firebase("https://nullform.firebaseio.com");
fb.authWithPassword(email, password, new AuthResultHandler());
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class AuthResultHandler implements Firebase.AuthResultHandler {
@Override
public void onAuthenticated(AuthData authData) {
System.out.println("authentication successful");
String uid = authData.getUid();
new RunTests(uid);
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {
System.out.println("authentication failed.");
}
}
}
PS:我正在我的电脑上使用 firebase-client-jvm 测试 firebase.
PS: i'm testing firebase using firebase-client-jvm on my pc.
推荐答案
你应该使用 Firebase 提供的事件:
You should use the events provided by Firebase:
fb.authWithPassword(email, password, new AuthResultHandler(){
@Override
public void onAuthenticated(AuthData authData) {
//do something if authentication successful
}
@Override
public void onAuthenticationError(FirebaseError error) {
//handle error
}
});
如果你真的想在主线程中等待,你可以这样做:
You could, if you really want to wait in the main do this:
void main(String[] args) {
boolean finished = false;
fb.authWithPassword(email, password, new AuthResultHandler(){
@Override
public void onAuthenticated(AuthData authData) {
finished = true;
}
});
while (!finished){
Thread.sleep(1);
}
}
这更像是一个伪代码.如果出现错误 (onAuthenticationError),它不会捕获中断的异常并永远阻塞.我也不推荐这个.忙着等待几乎从来都不是一个好主意.
Thats more of a pseudocode. It doesnt catch the interrupted exception and blocks forever if there is an error (onAuthenticationError). Also i would not recommend this. Busy waiting is almost never a good idea.
这篇关于如何等到所有线程完成执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!