一 概述
JDK中封装好的Java线程池实例有以下几种:
1.newFixedThreadPool
2.newSingleThreadExecutor
3.newCachedThreadPool
4.newScheduledThreadPool
5.newWorkStealingPool
二 线程池不同实例方法
1. newFixedThreadPool
/**
* @since 1.5
* @author Doug Lea
*/
public class Executors {
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue, using the provided
* ThreadFactory to create new threads when needed. At any point,
* at most {@code nThreads} threads will be active processing
* tasks. If additional tasks are submitted when all threads are
* active, they will wait in the queue until a thread is
* available. If any thread terminates due to a failure during
* execution prior to shutdown, a new one will take its place if
* needed to execute subsequent tasks. The threads in the pool will
* exist until it is explicitly {@link ExecutorService#shutdown
* shutdown}.
*
* @param nThreads the number of threads in the pool
* @param threadFactory the factory to use when creating new threads
* @return the newly created thread pool
* @throws NullPointerException if threadFactory is null
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
}
newFixedThreadPool中创建的核心线程数(第一个参数)corePoolSize和最大线程数(第二个参数)maxinumPoolSize是相等的且在初始化的时候就固定好的,线程池空闲线程任务的存活时间keepAliveTime默认为0且单位默认是毫秒,值得注意的是newFixedThreadPool中所用的存储阻塞队列为LinkedBlockingQueue,该队列默认情况下的容量是Integer.MAX_UALUE(2^31-1),所以该线程池存在一个问题是如果存储队列中的任务数越来越大,并且无法及时得到处理,即请求产生堆积的时候,会容易造成占用大量的内存,严重的情况下会导致内存溢出(Out Of Memory)。
2. newSingleThreadExecutor
/**
* Creates an Executor that uses a single worker thread operating
* off an unbounded queue. (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.) Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newFixedThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
*
* @return the newly created single-threaded Executor
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newSingleThreadExecutor中创建的核心线程数corePoolSize和最大线程数maxinumPoolSize是相等的且在初始化的时候就固定好为1,线程池空闲线程任务的存活时间keepAliveTime默认为0且单位默认是毫秒,值得注意的是newSingleThreadExecutor中所使用的存储阻塞队列也是LinkedBlockingQueue,该队列默认情况下的容量是Integer.MAX_UALUE(2^31-1),所以该线程池存在一个问题是如果存储队列中的任务数越来越大,并且无法及时得到处理,即请求产生堆积的时候,会容易造成占用大量的内存,严重的情况下会导致内存溢出(Out Of Memory)。
3. newCachedThreadPool
/**
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to {@code execute} will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources. Note that pools with similar
* properties but different details (for example, timeout parameters)
* may be created using {@link ThreadPoolExecutor} constructors.
*
* @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newCachedThreadPool的核心线程数corePoolSize为0,而线程最大数maxinumPoolSize是Integer.MAX_VALUE(2^31-1),且使用的是默认使用非平等策略且无法存储线程任务的阻塞队列——SynchronousQueue,所以当线程池中创建的线程数过多会导致内存溢出(Out Of Memory),不同的是该线程池中空闲线程任务的存活时间keepAliveTime默认为60且单位默认是秒。
4. newScheduledThreadPool
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
/**
* Creates a new {@code ScheduledThreadPoolExecutor} with the
* given core pool size.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
newScheduledThreadPool默认时自定义核心线程数corePoolSize的大小,且线程池中的最大线程数maxinumPoolSize的大小为Integer.MAX_VALUE(2^31-1),线程池空闲线程任务的存活时间keepAliveTime默认为0且单位默认是纳秒。不同的是该线程池所使用的线程任务存储队列为延迟队列DelayedWorkQueue()。
5. newWorkStealingPool
/**
* Creates a thread pool that maintains enough threads to support
* the given parallelism level, and may use multiple queues to
* reduce contention. The parallelism level corresponds to the
* maximum number of threads actively engaged in, or available to
* engage in, task processing. The actual number of threads may
* grow and shrink dynamically. A work-stealing pool makes no
* guarantees about the order in which submitted tasks are
* executed.
*
* @param parallelism the targeted parallelism level
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code parallelism <= 0}
* @since 1.8
*/
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
/**
* Creates a work-stealing thread pool using all
* {@link Runtime#availableProcessors available processors}
* as its target parallelism level.
* @return the newly created thread pool
* @see #newWorkStealingPool(int)
* @since 1.8
*/
public static ExecutorService newWorkStealingPool() {
return new ForkJoinPool
(Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
newWorkStealingPool是java8新加的一种线程池实例,该线程池中的线程可以产生子任务,如二叉树的遍历,会产生子任务去不断的遍历二叉树的子树,矩阵任务分成子任务中的4个小矩阵等。
更关键的是它可以窃取(Stealing)任务:当每个线程中存在很多子任务的时候,这些子任务会放到线程自己独有的队列中慢慢的去处理。如果存在三个线程任务A,B,C,当线程B和线程C处理完自己的线程任务之后并且新的任务分配的时候会处于空闲状态,此时的那当它们发现线程A中存在很多未执行的子任务就会主动窃取这些任务去执行,类是于并行执行。为了让并行执行的效率更好所以是不用加锁的,因为这些任务可能会被多个线程执行,不加锁会让多个线程高效的执行,且不保证执行顺序。
三 停止线程池的方法
/**
* @since 1.5
* @author Doug Lea
*/
public interface ExecutorService extends Executor {
/**
* Initiates an orderly shutdown in which previously submitted
* tasks are executed, but no new tasks will be accepted.
* Invocation has no additional effect if already shut down.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
*
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
void shutdown();
/**
* Attempts to stop all actively executing tasks, halts the
* processing of waiting tasks, and returns a list of the tasks
* that were awaiting execution.
*
* <p>This method does not wait for actively executing tasks to
* terminate. Use {@link #awaitTermination awaitTermination} to
* do that.
*
* <p>There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. For example, typical
* implementations will cancel via {@link Thread#interrupt}, so any
* task that fails to respond to interrupts may never terminate.
*
* @return list of tasks that never commenced execution
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
List<Runnable> shutdownNow();
/**
* Returns {@code true} if this executor has been shut down.
*
* @return {@code true} if this executor has been shut down
*/
boolean isShutdown();
/**
* Returns {@code true} if all tasks have completed following shut down.
* Note that {@code isTerminated} is never {@code true} unless
* either {@code shutdown} or {@code shutdownNow} was called first.
*
* @return {@code true} if all tasks have completed following shut down
*/
boolean isTerminated();
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return {@code true} if this executor terminated and
* {@code false} if the timeout elapsed before termination
* @throws InterruptedException if interrupted while waiting
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
}
1. shutdown():当线程调用该方法的时候,线程池不会立即停止,而是会保证正在执行的线程任务和存储队列中等待执行的任务执行完毕之后才会拒绝新分配的线程任务,然后才会停止。
2. isShutdown():判断线程池是否进入了ShutDown的状态,也就是执行shutdown()方法后就会立即返回true。
3. isTreminated():判断线程池是否完全停止。
4. awaitTermination(long timeout, TimeUnit unit):判断线程池在规定的时间内是否完全停止。
5. shutdownNow:线程池正在运行是执行该方法后,就会将正在执行的线程任务和存储队列中的任务直接返回到一个Runnable列表中,并停止线程池。