在主线程中保留一些进程,直到另一个线程完成其任务



我有一个类(比方说SocketClass(,它扩展了AsyncTask(我使用的是Sockets,这就是我使用AsyncTask的原因(。我在主线程上运行的另一个类上调用该类。

SocketClass socketClass = new SocketClass(input);
socketClass.execute();
System.out.println(socketClass.getOutput());

这是我的SocketClass

public class SocketClass extends AsyncTask < String, Void, Void > {
int output;
int input;
public Offload(int input) {
this.input = input;
}
public int getOutput() {
return output;
}
public void doSomething() {
// sockets related code
// set value to the output variable
}
@Override
protected Void doInBackground(String...voids) {
doSomething();
return null;
}
}

当我运行应用程序时,System.out.println(socketClass.getOutput());将在向output变量取值之前执行。是否只有在doSomething()方法中为output变量取值后才能执行System.out.println(socketClass.getOutput());?Stackoverflow中有一些解决方案,如Solution1和Solution2,但我害怕使用这些解决方案,因为我不知道它是否会对应用程序产生严重影响,因为我们想保留主线程中的一些进程

您可以在doInBackground完成后调用AsyncTask.get((来获取结果。

new SocketClass().execute().get();

注意:这将导致主线程在等待时挂起。

最新更新