優化APP性能(一) —通過線程池
前言
我們都知道如何在Android中創建一個線程,如下:
new Thread(new Runnable() {
@Override
public void run() {
...
}).start();
但是這樣子創建線程有一個缺點就是當一個項目非常大,很多地方都需要開啓子線程去執行任務的時候,不斷創建線程對於系統的開銷還是非常大的,一定程度上影響系統性能。那麼我們如何才能提高線程的吞吐量來優化系統性能尼?答案就是通過一個全局的線程池,如果我們可以規定整個團隊都用同一個線程池來執行耗時的任務那麼必定大大提高線程的吞吐量。
示例
public class GlobalThreadPool {
private static GlobalThreadPool instance = null;
private ExecutorService threadPool = Executors.newCachedThreadPool(new GlobalThreadFactory());
private GlobalThreadPool() {
}
private static class GlobalThreadFactory implements ThreadFactory {
private AtomicInteger threatIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setPriority(Thread.NORM_PRIORITY-2);
thread.setName("global_thread_"+threatIndex.getAndAdd(1));
return thread;
}
}
public static GlobalThreadPool getInstance() {
if (instance == null) {
synchronized (GlobalThreadPool.class) {
if (instance == null) {
instance = new GlobalThreadPool();
}
}
}
return instance;
}
public void execute(Runnable runnable) {
threadPool.execute(runnable);
}
}
我們在所有需要創建線程的地方都通過如下代碼替代直接開啓線程,如下:
GlobalThreadPool.getInstance().execute(new Runnable() {
@Override
public void run() {
...
}
});
後話
查看Android中的AsyncTask的源碼你也會發現,它其實也是通過一個全局線程池來執行後臺任務。如下:
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
至於有關線程池的相關知識網上有很多,在這裏我就不介紹了.