one Thread pool usage scenarios
two Common ways to pool threads
Let’s start with the basic construction parameters
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue
workQueue) { throw new RuntimeException(“Stub!” ); }
CorePoolSize: number of core threads in the thread pool.
MaximumPoolSize: specifies the maximum number of threads in the thread pool.
KeepAliveTime: Specifies the timeout period during which a non-core thread is idle before it is reclaimed
Unit: The unit of the time attribute above
WorkQueue: the queue of tasks in the thread pool, through the thread pool
ThreadFactory: a threadFactory that can be used to set thread names, etc. This parameter is generally not required.
2. Four types of thread pools in Android
2.1 FixThreadPool
A FixThreadPool has a fixed number of core threads that are not collected, and the threads are all executing while subsequent tasks are waiting
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public void excuteFixThreadPool()
{
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
fixedThreadPool.execute(runnable);
}
2.2 SingleThreadPool
SingleThreadPool has only one core thread and all tasks are executed sequentially in the same thread on a first-in, first-out basis
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
public void excuteSingleThreadPool()
{
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(runnable);
}
2.3 CachedThreadPool
CachedThreadPool does not have a core thread, but only a fee-core thread. New tasks create new threads. Threads that are idle for more than a specified time are recycled.
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public void excuteCachedThreadPool()
{
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(runnable);
}
2.4 ScheduledThreadPool
The number of core threads is fixed. There is no limit to the number of non-core threads (idle threads are immediately recycled).
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public void excuteScheduledThreadPool () { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(runnable, 1, TimeUnit.SECONDS); // The task will be executed after 1s