ThreadPoolExecutor更多线程=更慢的android

时间:2014-01-12 13:07:44

标签: java android

   BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
                ThreadPoolExecutor ex = new ThreadPoolExecutor(1,1, 1L, TimeUnit.MINUTES, queue);

                final HashMap<String,Response> responses = new  HashMap<String,Response>();

                ex.execute(new Runnable() {
                    @Override
                    public void run() {
                        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE);
                        Response response = getService().getProducts();
                        responses.put("1",response);


                    }
                });
....
....

...


 ex.shutdown();
 ex.awaitTermination(1000, TimeUnit.DAYS);
 long  time2 = System.currentTimeMillis();

我提出了很多要求,我希望在完成后得到通知。

使用带有1个线程的ThreadPoolExecutor在旧设备上测试android 2.3 gingerbead需要1-1.2秒。使用4个线程需要更多的时间4-5秒!。

在galaxy tab 3上测试它需要一个线程100毫秒,4个需要60毫秒。

为什么会这样?

1 个答案:

答案 0 :(得分:5)

无论您创建多少个线程,您的处理器中只有这么多物理内核。

旧设备可能有一个核心,所以有了更多的线程,它必须不断地在线程之间跳转来处理它们。

新设备有多个内核,因此可以将线程分散到它们上面并并行运行。

通常,对于密集型任务,您应该永远不要启动比拥有核心更多的线程。对于偶尔运行的任务,可以使用更多的线程,但是像后面有一个线程池的ScheduledExecutor更好。

相关问题