优化APP性能(一)

优化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;
    }

至于有关线程池的相关知识网上有很多,在这里我就不介绍了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值