線程池有以下的優(yōu)點(diǎn):
- 重用線程池中的線程死遭,避免因?yàn)榫€程的創(chuàng)建和銷毀所帶來的性能上的開銷
- 能有效控制線程池的最大并發(fā)數(shù)草巡,避免大量的線程之間因?yàn)榛ハ鄵屨枷到y(tǒng)資源而導(dǎo)致阻塞現(xiàn)象
- 能夠?qū)€程池就行簡單的管理,并提供定時執(zhí)行以及指定間隔循環(huán)
線程池介紹
ThreadPoolExecutor是線程池的真正實(shí)現(xiàn)
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default rejected execution handler.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
ThreadPoolExecutor執(zhí)行任務(wù)是遵循的規(guī)則
image.png
參數(shù)設(shè)置
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
線程池的分類
·FixedThreadPool:
數(shù)量固定的核心線程池,沒有超時機(jī)制。任務(wù)隊列大小沒有限制辫继。
·CachedThreadPool:
線程數(shù)量不定,只有非核心賢臣俗慈,最大線程數(shù)位Integer.MAX_VALUE姑宽。它比較適合執(zhí)行大量的耗時較少的任務(wù)
·ScheduledThreadPool:
核心線程數(shù)量固定,非核心線程數(shù)量沒有限制姜盈。適合執(zhí)行定時任務(wù)和具有固定周期的重復(fù)任務(wù)低千。
·SingleThreadExecutor:
只有一個核心線程