Android上的多个同时HTTP请求

时间:2012-12-06 21:20:52

标签: android executorservice apache-httpclient-4.x executor threadpoolexecutor

因此,我在AsyncTask中有下面的代码,并希望调用7个不同的异步HTTP请求。一切正常,所有7个execute()方法同时开始(花几毫米,这很棒)。

不幸的是,使用此方法所需的时间是aprox。 16秒如果我排除所有执行程序的东西并在原始工作程序Asynctask上调用HTTP下载方法,则需要aprox。 9秒因此,它实际上需要较少的时间顺序而不是并发。任何想法为什么会这样?也许是服务器端的东西?也许是因为执行者是在Asynctask上启动的?非常感谢!

            MyExecutor executor = new MyExecutor(7, 7, 40000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
            executor.execute(new Runnable()
            {
                @Override
                public void run()
                {
                    try {downloadSplashScreenJsonData();}
                    catch (Exception e)
                    {
                        Log.e(TAG, "Could not download splashscreen data.");
                        e.printStackTrace();
                    }
                }
            });
            // after another 6 executor.execute() calls,
            executor.shutdown();
            executor.awaitTermination(40000, TimeUnit.MILLISECONDS); 

    class MyExecutor extends ThreadPoolExecutor
    {


    public MyExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        prestartAllCoreThreads();
        // TODO Auto-generated constructor stub

    }

    @Override
    public void execute(Runnable command) {
        super.execute(command);
        Log.e(TAG, "execute()");
        Log.e(TAG, "no of thr: " + getActiveCount());

    }
}

2 个答案:

答案 0 :(得分:0)

不要随便知道,但我观察到:

  1. 什么是restartAllCoreThreads,为什么要在构造函数中调用它?不要开始 你需要它们之前的线程(而LinkedBlockingQueue&lt;&gt;会为你节省空间)。
  2. 你真的需要在AsyncTask中运行它吗? Threadpool中的线程不会运行 UI线程,以及运行UI线程是AsyncTask的主要优势。如果你 我真的想在后台完成所有这些工作,使用IntentService。

答案 1 :(得分:0)

当我回顾这件事时,我想补充一些信息。

首先,应用程序所需的用例非常迟钝和繁琐(但是嘿,客户,你能做什么......)。就像Joe上面所述,我现在不会在一百万年内下载Asyncs的数据。如果可能的话,应该使用某种服务来下载所需的数据。

其次,我最终使用RoboSpice库(它还提供了缓存)而不是Asyncs。它仍然不如在服务上运行,但它比准系统版本更优化。可能想检查一下。