本文主要是介绍java 线程池初步涉足,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先看以下代码,是我们创建线程池的一种方式:
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
可以进入Executors类看一下,java创建线程池的四种方式,分别有以下四个大类:
(1)newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程(空闲线程超过存活时间的可以回收),若无可回收,则新建线程。
(2)newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
(3)newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
(4)newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
当然在Executors中创先以上四种线程池的方式还有很多,一会有所涉及。
我们现在进入Executors类看看创建上述四种线程池有哪些方式:
(1)newFixedThreadPool
/*** 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线程池的,一种是直接传入线程的个数,另外一种是传进线程的个数,还有线程工厂(ThreadFactory)。有些任务需求对于如何创建线程有自己安排,所以需要传入自己实现ThreadFactory接口的线程工厂类。仔细看,其实这两个方法都使用了类ThreadPoolExecutor。可以去类ThreadPoolExecutor中看看里面构造函数中参数的意思,其构造函数代码如下:可以看到他调用了this(....)构造函数,我顺便把他底层的构造函数都写在后面,方便查看。
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);} /*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @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* @param handler the handler to use when execution is blocked* because the thread bounds and queue capacities are reached* @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} or {@code handler} is null*/public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)
这里面一共有六个参数,分别如下:
corePoolSize是线程池中所维持的线程池大小。这些线程即使是空闲状态,也会存在于线程池中,不会被销毁。这个线程池的核心线程数也可以设置为0,像newCachedThreadPool中就是将核心线程数设置为0的。
maxPoolSize是线程池的最大线程数。这个最大线程数是对于或等于核心线程数的,当你用newFixedThreadPool和newSingleThreadPool时,核心线程数和最大线程数是相等的,这一点你可以在这两种线程池的构造函数中得到验证。
keepAliveTime是用来约束某种线程的生存时间的,这个某种线程是什么意思呢,当线程池所使用的线程数设为n,这个某种线程是一类线程,就是n-corePoolSize的线程,就是超过核心线程数的线程。当线程池所创建的线程数大于核心线程数时,此时会计算当前的这些线程中哪些线程是空闲的,当空闲时间超过这个设定的keepAliveTime时,该线程就会被回收。
unit就是时间单位
workQueue:工作队列,该队列是当核心线程数已经使用完了,之后提交的任务就将放入这个工作队列,尤其需要注意的是,只有当你用execute()方法提交的任务才会放在这个工作队列中。一般到队列满的时候,才会创建先的线程来执行任务,当然要保证线程池的所有线程数小于或等于最大线程数。
threadFactory:线程工厂用于创建线程的。有些需求可能需要自己创建的线程。
handler:是拒绝策略,也叫饱和策略,当线程池中的线程数达到maxPoolSize,并且workQueue(有界队列)已经满了,就需要采用饱和策略了,对于新提交的任务是直接拒绝还是怎么样,是在这边设置的。
这边了解了底层创建线程池的参数,回过头来看看newFixedThreadPool是怎么创建线程池的:
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}
newFixedThreadPool是是有一个参数,就是线程数nThread。这个参数用于设置核心线程数和最大线程数,其中的工作队列是LinkedBlockingQueue,这个队列是链表实现的,也就是说该工作队列不会满,除非你限制他的长度。而且该线程池中的最大线程数就是核心线程数。
接着我们看看其他几个线程池的构造方式。
(2)newSingleThreadExecutor
看看构造函数,核心线程数和最大线程数都是1,生存时间0,也是LinkedBlockingQueue
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}
(3)newCachedThreadPool
这边有两个构造函数,就是传入承诺书不一样,一个啥也没传,一个穿了线程工厂。最大线程数是Integer的最大值,核心线程数为0,线程最大空闲时间为60秒。工作队列是SynchronousQueue,这个queue是即是交付的,就是任务一到就创建线程去执行。整个工作机制如下:来一个任务就创建线程去执行,当然有空闲线程让这些空闲线程去执行,空闲线程有一个60s生存时间。
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}/*** Creates a thread pool that creates new threads as needed, but* will reuse previously constructed threads when they are* available, and uses the provided* ThreadFactory to create new threads when needed.* @param threadFactory the factory to use when creating new threads* @return the newly created thread pool* @throws NullPointerException if threadFactory is null*/public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),threadFactory);}
(4)newScheuledThreadPool
/*** 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 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* @param threadFactory the factory to use when the executor* creates a new thread* @return a newly created scheduled thread pool* @throws IllegalArgumentException if {@code corePoolSize < 0}* @throws NullPointerException if threadFactory is null*/public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);}
这个定时线程池底层使用了ScheuledThreadPoolExecytor类,那我们去看看这个类是怎么构造的
/*** 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());}
该类继承 extends ThreadPoolExecutor,所使用的参数就是线程池核心线程数,最大线程数是Integer的最大值,队列用了延迟队列,没有生存时间这一说法。
这篇关于java 线程池初步涉足的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!