线程池封装类—借鉴ImageLoader的线程工厂

在Android开发过程中免不了需要使用异步线程,但是在项目中大量使用

            new Thread() {
                public void run() {
                    // do sth
                };
            }.start();

会造成很多野线程,不但不易维护,在性能上也是有一定折扣。
ps : 项目中用的线程比较少就没必要了,毕竟开个线程池比开个线程更好资源


下面就是,笔者借鉴ImageLoader的线程工厂,封装的一个线程池管理类,有需要的直接用吧

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池管理类 
 * 使用:ThreadManager.getPoolProxy().execute(runnable);
 * 
 * @author brian512
 */
public class ThreadManager {
    private static final String TAG = ThreadManager.class.getSimpleName();
    private static ThreadPoolProxy poolProxy;

    public static ThreadPoolProxy getPoolProxy() {
        if (poolProxy == null) {
            synchronized (TAG) {
                if (poolProxy == null) {
                    int processorCount = Runtime.getRuntime().availableProcessors();
                    int maxAvailable = Math.max(processorCount * 3, 10);
                    // 线程池的核心线程数、最大线程数,以及keepAliveTime都需要根据项目需要做修改
                    // PS:创建线程的开销 高于 维护线程(wait)的开销
                    poolProxy = new ThreadPoolProxy(processorCount, maxAvailable, 15000);
                }
            }
        }
        return poolProxy;
    }

    public static class ThreadPoolProxy {

        private ThreadPoolExecutor  threadPoolExecutor;     // 线程池

        private int                 corePoolSize;           //线程池中核心线程数

        private int                 maximumPoolSize;        //线程池中最大线程数,若并发数高于该数,后面的任务则会等待

        private int                 keepAliveTime;          // 超出核心线程数的线程在执行完后保持alive时长

        /**
         * @param keepAliveTime time in milliseconds
         */
        public ThreadPoolProxy(int corePoolSize, int maximumPoolSize,
                int keepAliveTime) {
            this.corePoolSize       = corePoolSize;
            this.maximumPoolSize    = maximumPoolSize;
            this.keepAliveTime      = keepAliveTime;
        }

        public void execute(Runnable runnable) {
            if (runnable == null) {
                return;
            } else {
                if (threadPoolExecutor == null || threadPoolExecutor.isShutdown()) {
                    synchronized (TAG) {
                        if (threadPoolExecutor == null || threadPoolExecutor.isShutdown()) {
                            threadPoolExecutor = createExecutor();
                            threadPoolExecutor.allowCoreThreadTimeOut(false); // 核心线程始终不消失
                        }
                    }
                }
                threadPoolExecutor.execute(runnable);
            }
        }

        private ThreadPoolExecutor createExecutor() {
            return new ThreadPoolExecutor(corePoolSize,
                    maximumPoolSize, keepAliveTime,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue(),
                    new DefaultThreadFactory(Thread.NORM_PRIORITY, "csdn-pool-"), 
                    new AbortPolicy());
        }
    }

    /**
     * 创建线程的工厂,设置线程的优先级,group,以及命名
     */
    private static class DefaultThreadFactory implements ThreadFactory {

        private static final AtomicInteger poolNumber   = new AtomicInteger(1); // 线程池的计数

        private final AtomicInteger threadNumber        = new AtomicInteger(1); // 线程的计数

        private final ThreadGroup   group;
        private final String        namePrefix;
        private final int           threadPriority;

        DefaultThreadFactory(int threadPriority, String threadNamePrefix) {
            this.threadPriority = threadPriority;
            this.group = Thread.currentThread().getThreadGroup();
            namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            t.setPriority(threadPriority);
            return t;
        }
    }
}

我写的CSDN博客客户端介绍:http://blog.csdn.net/brian512/article/details/43168141

点击查看应用详情

你可能感兴趣的:(Android小知识,Android框架)