可调用和未来延迟android主线程

时间:2019-02-19 09:30:17

标签: android future callable

我想通过可调用和将来从服务中获取一些数据。这是我的代码之一:

@Override
public void getCIFilesType(Consumer<String> consumer) {
    try {
        consumer.accept(serviceExecutor.submit(() ->
                service.getCi(EsupFactory.getConfigString(SETTING_ROOT_CI) + "GetCI",
                        translator.makeCiJsonObject("PCiName", "CI_FilesType")).execute())
                .get().body().string());
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我有10个像上面这样执行的方法。我使用Executor服务运行callable

ExecutorService serviceExecutor = Executors.newSingleThreadExecutor();

我是我的活动,我有一个菜单,然后单击菜单中的一项,片段就是一项活动。所有线程任务都立即在onViewCreated中的片段中开始

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    presenter.getCis();
}

但是,当我单击菜单项UI时,直到所有任务关闭然后事务关闭为止。这不是我第一次遇到这个问题。每次我使用可调用和执行器服务时,我都不知道为什么UI会变得卷曲!

这是探查器:

enter image description here

  

有人对我有指导!?请不要告诉我使用asyncTask:-)

     

什么是读取行?在ui线程中,我只是执行事务而不执行长时间运行的任务!!!

1 个答案:

答案 0 :(得分:1)

之所以会这样,是因为您将来会在 execute()方法返回的将来调用 get()。根据文档,

  

如果您想立即阻止等待任务,则可以使用result = exec.submit(aCallable).get();

形式的构造

因此,即使您使用后台线程,也可以通过调用 get 来阻塞主线程,直到后台线程完成任务为止。

为避免UI垃圾,您应该使用回调。

相关问题