【问题标题】:Wait for future get result in a handler thread在处理程序线程中等待未来获取结果
【发布时间】:2016-11-30 03:58:02
【问题描述】:

我将三个任务提交给执行程序实例。我需要通知两个活动同步过程结束。所以我就这样实现了

公共类 SyncManager {

Handler syncHandler;

public SyncManager() {
    initHandler();
}

private void initHandler() {
    HandlerThread ht = new HandlerThread("syncHandler");
    ht.start();
    syncHandler = new Handler(ht.getLooper()) {
        private ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);

        public void handleMessage(Message msg) {

            Future future1 = executor.submit(new ImageRetrieverTask());
            Future future2 = executor.submit(new FileRetrieverTask());
            Future future3 = executor.submit(new AudioRetrieverTask());


            try {
                Object result1 = future1.get();
                Object result2 = future2.get();
                Object result3 = future3.get();

      // Here i can use EventBus to notify observers of the completion of the sync
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        };
    };
}

public void performSync() {
    syncHandler.sendEmptyMessage(1);
} }

当 SyncManager 类被分配时,处理程序被初始化。 当调用 performSync 方法时,它基本上会向处理程序发送一条消息,以将所有与同步相关的任务添加到执行程序,以便它可以执行它们。处理程序是等待期货结束的后台循环,以便可以通过 EventBus 分派通知。处理程序是为了让我可以在后台线程中等待。

我觉得这是一种 hacky 方式。有更好的方法吗?

非常感谢任何帮助。 谢谢!

【问题讨论】:

标签: java android concurrency handler


【解决方案1】:

如果你不使用Future结果并且不重复使用ThreadPoolExecutor,你可以通过调用ExecutorService.awaitTermination(long timeout, TimeUnit unit)来等待所有提交的任务完成

【讨论】:

    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2014-06-24
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多