优化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;
}
至于有关线程池的相关知识网上有很多,在这里我就不介绍了.