线程池总结

138 阅读2分钟

参考自:Java/Android中的线程池,看这一篇就够了!(超详细)

1.线程池定义

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.

2.线程池中的线程分类

核心线程:长期存活,即使空闲也不会被销毁
普通线程:闲置时间超过设定时间将被销毁.

3.线程的具体行为和几个重要参数

corePoolSize:线程池中核心线程数量
maximumPoolSize:线程池允许保留最大线程数
keepAliveTime:线程池中普通线程的存活时间

4.线程池的作用

减少频繁创建和销毁线程所带来的开销.
任务的管理

5.线程池的一般使用步骤

使用Executors中的工厂方法来获取ExecutorService实例.
使用ExecutorService的executor(runnable)或者submit(runnable)方法来添加任务.

var es=Executors.newSingleThreadExecutor()
es.execute {
    println("----------")
}

5.线程池的4种分类

1.SingleThreadExecutor:单线程线程池,corePoolSize=1,maxmumPoolSize=1
使用场景:当多个任务需要访问同一个资源的时候.

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>()));
}

2.FixedThreadPool:固定容量的线程池,corePoolSize=maxmumPoolSize=n
使用场景:明确同时执行任务数量时.

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());
}

3.CachedThreadPool:缓存线程池,corePoolSize=0,maxmumPoolSize=Integer.MAX_VALUE
使用场景:处理大量耗时较短任务.

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
    60L, TimeUnit.SECONDS,
    new SynchronousQueue<Runnable>());
}

4.ScheduledThreadPool:定时线程池,corePoolSize=n,maxmumPoolSize=Integer.MAX_VALUE
使用场景:处理延时任务.

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

6.线程池的工作流程

当调用ThreadPoolExecutor.execute(runnable)的时候,会进行一下判断(这里不考虑延时任务):
1.如果线程池中运行的线程数少于核心线程数,则新建一个核心线程,并执行该任务.
2.如果线程池中运行的线程数大于等于corePoolSize,并且任务队列未满时,则添加到待执行的队列中,等待执行, 否则新建非核心线程,并在该线程中执行任务.
3.如果线程数=maxnumPoolSize,则拒绝这个任务.