Android线程池简介和基本应用

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

一、为什么使用线程池?

1.线程的创建和销毁由线程池维护,节约系统的开销;
2.执行大量异步任务时,线程池可以提高性能;
3.控制线程最大并发数,线程的定时任务和单线程的执行任务。

二、Android线程池框架结构主要包括3个部分:

1.任务:需要实现的接口类:Runnable或Callable
2.任务的执行器:核心接口类Executor
3.执行器的创建者:工厂类Executors(包括ThreadPoolExecutor,ScheduledThreadPoolExecutor)

三、线程池使用方法和参数解析

1、初始化一个任务执行器。

private static final int CORE_POOL_SIZE = 4;
private static final int MAX_POOL_SIZE = 8;
private static final int KEEP_ALIVE_TIME = 10;
private final Executor mExecutor;
mExecutor = new ThreadPoolExecutor(
       CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,
        TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
        new PriorityThreadFactory("thread-pool", Process.THREAD_PRIORITY_BACKGROUND));

参数解析:
//CORE_POOL_SIZE:核心线程,即使它们处在空闲状态,也要保留在池中的线程数
//MAX_POOL_SIZE:池中允许的最大线程数
//KEEP_ALIVE_TIME:当线程数大于核心线程时,多余线程在终止之前等待新任务的最长时间
//TimeUnit.SECONDS:keepAliveTime的时间单位,这里为秒
//new LinkedBlockingQueue():workQueue,在执行任务之前用于保存任务的队列,这里的LinkedBlockingQueue是一种有界的阻塞队列
//new PriorityThreadFactory(“thread-pool”, Process.THREAD_PRIORITY_BACKGROUND):工厂类,执行程序创建的新线程使用的工厂(该参数可不设置)

2.创建一个简单任务

private class Worker implements Runnable{
    @Override
    public void run(){
        //do something
    }
}

3.执行任务。

Worker w = new Worker();
mExecutor.execute(w);

四、线程池类封装和应用

线程池的类:

/**
 * Offloads work from other threads by running it in a background thread.
 */
public class BackgroundExecutor {

    private static final BackgroundExecutor sInstance = new BackgroundExecutor();

//查看newFixedThreadPool实际上是使用上述new ThreadPoolExecutor创建
    private final ExecutorService mExecutorService = Executors.newFixedThreadPool(2);

    /**
     * @return the static instance of the background executor.
     */
    public static BackgroundExecutor get() {
        return sInstance;
    }

    /**
     * Runs the given {@param callable} on one of the background executor threads.
     */
    public <T> Future<T> submit(Callable<T> callable) {
        return mExecutorService.submit(callable);
    }

    /**
     * Runs the given {@param runnable} on one of the background executor threads.
     */
    public Future<?> submit(Runnable runnable) {
        return mExecutorService.submit(runnable);
    }

    /**
     * Runs the given {@param runnable} on one of the background executor threads. Return
     * {@param result} when the future is resolved.
     */
    public <T> Future<T> submit(Runnable runnable, T result) {
        return mExecutorService.submit(runnable, result);
    }
}

应用:

private final BackgroundExecutor mBackgroundExecutor;

mBackgroundExecutor = BackgroundExecutor.get();

mBackgroundExecutor.submit(new Runnable() {
    @Override
    public void run() {
		//do something
    }
});

猜你喜欢

转载自blog.csdn.net/Sunxiaolin2016/article/details/94737304