2015-05-18 44 views

回答

4

根據處理器數量選擇Threads的數量是一個很好的解決方案,因爲它根據運行應用程序的設備的硬件進行擴展。這方面的一個很好的例子可以在AsyncTasksource code發現:

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); 
private static final int CORE_POOL_SIZE = CPU_COUNT + 1; 
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; 
private static final int KEEP_ALIVE = 1; 

private static final ThreadFactory sThreadFactory = new ThreadFactory() { 
    private final AtomicInteger mCount = new AtomicInteger(1); 

    public Thread newThread(Runnable r) { 
     return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); 
    } 
}; 

private static final BlockingQueue<Runnable> sPoolWorkQueue = 
     new LinkedBlockingQueue<Runnable>(128); 

public static final Executor THREAD_POOL_EXECUTOR 
     = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 
     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 

我會認爲這是一個最佳實踐的解決方案。

如果您想更好地瞭解他們如何使用ThreadPoolExecutor,可以查看AsyncTaskhere的源代碼。