Java线程池原理(多线程)
来源:互联网 发布:淘宝内衣模特 编辑:程序博客网 时间:2024/06/07 02:12
一、JDK四种线程池
1、ExecutorService .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 * <tt>newFixedThreadPool(1)</tt> 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>())); }同时有一个多态方法
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory)); }
2、ExecutorService newFixedThreadPool(int nThreads) //一种固定线程数量的线程池,超过数量的线程将保存在等待队列中,源码如下
/** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. At any point, at most * <tt>nThreads</tt> 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}.*/ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
我们注意到newFixedThreadPool方法还有一个多态方法,第二参数是ThreadFactory,后面再讲,先记下。
/* @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 <tt>nThreads <= 0</tt> */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
3、可缓存线程的线程池
/** * 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 <tt>execute</tt> 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>()); }多态方法
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); }
4、一个可定时执行的单一线程线程池
/** * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. * (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 * <tt>newScheduledThreadPool(1)</tt> the returned executor is * guaranteed not to be reconfigurable to use additional threads. * @return the newly created scheduled executor */ public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); }我们看到他内部调用了ScheduledThreadPoolExecutor这个线程池类继承ThreadPoolExcute,ThreadPoolExcute继承自AbstractExcuteService,这些线程池的继承关系和家族生态,需要再写一篇详细研究。
二、ThreadPoolExcute内部原理
首先看源码,ThreadPoolExcute类有很多个构造方法,参数不一,如果用户异常处理Handler没有定义,系统使用默认处理器
/** * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial * parameters. * * @param corePoolSize the number of threads to keep in the * pool, even if they are idle. * @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 keepAliveTime * argument. * @param workQueue the queue to use for holding tasks before they * are executed. This queue will hold only the <tt>Runnable</tt> * tasks submitted by the <tt>execute</tt> 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 corePoolSize or * keepAliveTime less than zero, or if maximumPoolSize less than or * equal to zero, or if corePoolSize greater than maximumPoolSize. * @throws NullPointerException if <tt>workQueue</tt> * or <tt>threadFactory</tt> or <tt>handler</tt> are null. */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
对参数的一些解释,excute开始执行后,如果线程数没有达到corePoolSize则创建线程,如果达到了corePoolSize则将新的线程加入workQueue,如果线程数达到workQueue规定数量,则线程池扩容到maximumPoolSize,如果超过maximumPoolSize则执行异常处理器RejectedExcutionHanler。
ps:还有很多知识,这篇文章只是一个开头,线程中的每个知识点都需要专门文章来详细解读。
0 0
- Java线程池原理(多线程)
- Java 多线程线程池 - 线程池原理
- Java 多线程线程池 - 线程池原理
- Java 多线程9:线程池实现原理
- Java多线程--线程池的原理分析
- Java 多线程线程池 - 线程池原理(1)
- Java 多线程线程池 - 线程池原理(2)
- Java多线程线程池(3)--线程池原理
- Java多线程----Java 线程池的原理与实现
- Java多线程----Java 线程池的原理与实现
- java多线程总结五:线程池的原理及实现
- java多线程总结五:线程池的原理及实现
- java多线程总结五:线程池的原理及实现
- java多线程总结五:线程池的原理及实现
- java多线程总结之:线程池的原理及实现
- java多线程 :线程池的原理及实现
- java多线程总结五:线程池的原理及实现
- Java 多线程:分析线程池的实现原理
- 封装
- 用几何画板演示三角转子发动机原理的方法
- jstl自定义函数
- 第十周(2)判断回文数
- uc/os-II 分析 (3)
- Java线程池原理(多线程)
- 冒个泡
- Configuration with name 'default' not found.
- Centos 7静态IP设置
- 第十周项目二——回文数(2)
- Maven编译时异常
- css&js 控制输入
- git linux安装
- web安全基础——CSRF