【问题标题】:AsyncHttpClient with ThreadPoolExecutor to know when all tasks are finished?AsyncHttpClient 与 ThreadPoolExecutor 知道所有任务何时完成?
【发布时间】:2013-02-20 20:44:08
【问题描述】:

我正在使用AsyncHttpClient 来获取一些 JSON。我的方法将解析 JSON 并触发另一个 get 请求,所以我实际上不知道有多少线程正在运行。经过一番搜索,我想我可以使用ThreadPoolExecutor 知道我的所有线程何时完成,这样我就可以写入数据库。如果我使用AsyncHttpClient.get(),执行者如何知道我提交了作业?

AsyncHttpClient client = new AsyncHttpClient();
int limit = 20;
BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(limit);
ThreadPoolExecutor executor = 
                        new ThreadPoolExecutor(limit, limit, 20, TimeUnit.SECONDS, q);
client.setThreadPool(executor);
parseSilo(url, context); // this fires client.get() ... as it encounters urls in JSON feed
executor.shutdown();
while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
      Log.e(TAG, executor.getTaskCount() + " tasks left");
}

【问题讨论】:

    标签: android android-asynctask threadpoolexecutor


    【解决方案1】:

    我看不到您将工作提交给ThreadPoolExecutor

    示例代码:

    executor.execute(new Runnabale() {
        public void run() {
           // your job code
        }
    });
    

    编辑:

    我刚刚注意到您覆盖了AsyncHttpClient 的默认ThreadPoolExecuter,因此在发出请求时将使用它(例如get),它应该可以在没有明确向executor 发送任何内容的情况下工作

    您还可以覆盖方法terminated(),而不是循环直到所有任务完成。

    【讨论】:

    • 对,所以也许我的问题不清楚。如果我使用 AsyncHttpClient.get(),执行者如何知道我提交了作业?
    • 您将覆盖AsyncHttpClient 的默认ThreadPoolExecuter,因此在发出请求时将使用它
    • 好吧,我想我现在明白了,但是因为 AsyncHttpClient.get() 是一个异步调用,这很糟糕吗?
    • 我不明白你的意思,但是这很糟糕吗? AsynchHttpClient 使用 ThreadPoolExecuter 以获得 asynch 方法
    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    相关资源
    最近更新 更多