在Android-27查看源码
线程池的创建,查看Executors的源码:
1、newFixedThreadPool:创建一个线程池,最多可以创建nThreads个线程,然后可以对其进行复用。在任意时刻,最多有nThreads个线程会被激活执行任务。
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(), threadFactory);
}
2、newWorkStealingPool:创建一个带并行级别的线程池,并行级别决定了同一时刻最多有多少个线程在执行,如不传并行级别参数,将默认为当前系统的CPU个数。
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool (parallelism,ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
}
3、newSingleThreadExecutor:创建一个执行器,使用单个线程去处理,和newFixedThreadPool相比,它不会重新创建额外的线程。
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS, newLinkedBlockingQueue<Runnable>(),threadFactory));
}
4:newCachedThreadPool:创建一个线程池按需去创建线程,但是当之前创建的线程有可用的时候会去复用已经创建的线程,否则重新创建线程
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),threadFactory);
}
5、newSingleThreadScheduledExecutor:创建单个线程执行器去执行可计划的任务(比如延迟、重复),它不会再重新创建线程,除非它的单个线程在执行时失败导致线程关闭,才会创建新的线程。
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1, threadFactory));
}
6、newScheduledThreadPool:创建一个线程池,可以执行有计划的任务(比如延迟、重复),它会保持指定数量的线程,即使它们处于闲置状态
public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
其中ThreadPoolExecutor源码,可以参考ThreadPoolExecutor源码 - 简书
参考文章:https://blog.csdn.net/a369414641/article/details/48342253
网友评论