定义
Java通过Executors提供四种线程池,分别为:
- newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
- newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
- newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
- newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
使用
static ThreadPoolExecutor threadPoolExecutor;
private static final BlockingDeque<Runnable> sPoolWorkQueue =
new LinkedBlockingDeque<>(4);
//Queue 的参数
//BlockingQueue:先进先出的一个附列FIFO
//SynchronousQueue:线程安全的队列,它里面是没有固定的缓存的(Okhttp使用的)
//PriorityBlockingQueue:无序的可以根据优先级进行排序,指定的对象要实现Comparable作比较
static {
threadPoolExecutor = new ThreadPoolExecutor(
4,//核心线程数,就是线程池里面的核心线程数量
10,//最大线程数,线程池中的最大线程数
60,//线程存活的时间,没事干的时候空闲的存活时间,超过这个时间线程就会被销毁
TimeUnit.SECONDS,//线程存活时间的单位
sPoolWorkQueue//线程队列
);
}
public void test(){
threadPoolExecutor.execute(runnnable);
}
网友评论