android - 可调用和未来延迟android主线程
问题描述
我想通过可调用和未来从服务中获取一些数据。这是我的代码之一:
@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
时,直到所有任务都停止,然后事务就停止了。这不是我第一次遇到这个问题。每次我使用 callable 和 executor 服务时,我都不知道为什么 UI 会卷曲!!!!
这是探查器:
有人给我一些指导!?请不要告诉我使用 asyncTask :-)
什么是读线??在ui线程中我只是做事务而不执行长时间运行的任务!!!
解决方案
发生这种情况是因为您在execute()方法返回的未来调用get() 。根据文档,
如果您想立即阻止等待任务,可以使用 result = exec.submit(aCallable).get(); 形式的结构。
因此,即使您使用后台线程,也可以通过调用get阻塞主线程,直到后台线程完成您的任务。
为避免 UI 垃圾,您应该使用回调。
推荐阅读
- azure-devops - Azure DevOps:更改拥有项目的组织
- c# - 如何在动画期间冻结控件上的滚动?
- ios - CoreBluetooth API MISUSE - iOS 13 中的 CBCentralManager 问题,如 Siri Shortcuts
- php - mgp25 Instagram-API API 请求过多
- javascript - 将数据从对象传递到数组
- javascript - 使用 Rest Get Api 消耗数据时出现 CORS 错误
- php - Voyager 安装 Laravel 上的外键约束格式不正确
- python - 如何编写一个程序来打印用户必须输入的十个数字的总和
- sql - 根据同一表中的其他列值更新列
- javascript - 图表 js 未在页面上加载