【问题标题】:Hold some process in the Main Thread until another thread finishes its tasks在主线程中保留一些进程,直到另一个线程完成其任务
【发布时间】:2021-03-14 02:05:45
【问题描述】:

我有一个扩展AsyncTask 的类(比如说SocketClass)(我使用的是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中有一些解决方案,例如Solution1Solution2,但我不敢使用它们,因为我不知道它是否会对应用程序产生严重影响,因为我们想保留一些在主线程中的进程

【问题讨论】:

  • 如果主线程需要等待结果,你为什么要在异步任务/线程上旋转?这似乎违背了多线程的目的。如果您仍然要等待结果,您能否简化您的解决方案并删除 AsyncTask 并仅在主线程上执行?
  • 我不得不使用异步任务,因为应用程序不允许在主线程上运行与套接字相关的代码

标签: java android multithreading sockets


【解决方案1】:

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

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

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

【讨论】:

  • 还有其他不影响主线程的解决方法吗?
  • 在主线程上还需要做什么?它不会“影响”主线程——工作将在另一个线程上完成。但是在完成之前,在主线程上没有什么可做的,至少从你的描述来看,所以你必须等待结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多