四种线程池分别是:newCachedThreadPool、newFixedThreadPool 、newScheduledThreadPool 和newSingleThreadExecutor ,下面对这几个线程池一一讲解。java
源码:缓存
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
newCachedThreadPool的方法中是返回一个ThreadPoolExecutor实例,从源码中能够看出该线程池的特色:架构
一、该线程池的核心线程数量是0,线程的数量最高能够达到Integer 类型最大值;ide
二、建立ThreadPoolExecutor实例时传过去的参数是一个SynchronousQueue实例,说明在建立任务时,若存在空闲线程就复用它,没有的话再新建线程。学习
三、线程处于闲置状态超过60s的话,就会被销毁。this
用法:spa
public static void main(String[] args) { //定义ExecutorService实例 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int index = i; try { Thread.sleep(index * 1000); } catch (InterruptedException e) { e.printStackTrace(); } //调用execute方法 cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread() + ":" + index); } }); } }
上面的代码由于每次循环都是隔一秒执行,这个时间足够以前的线程工做完毕,并在新循环中复用这个线程,程序的运行结果以下:线程
Thread[pool-1-thread-1,5,main]:0 Thread[pool-1-thread-1,5,main]:1 Thread[pool-1-thread-1,5,main]:2 Thread[pool-1-thread-1,5,main]:3 Thread[pool-1-thread-1,5,main]:4 Thread[pool-1-thread-1,5,main]:5 Thread[pool-1-thread-1,5,main]:6 Thread[pool-1-thread-1,5,main]:7 Thread[pool-1-thread-1,5,main]:8 Thread[pool-1-thread-1,5,main]:9
源码:code
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
线程池特色:接口
一、线程池的最大线程数等于核心线程数,而且线程池的线程不会由于闲置超时被销毁。
二、使用的列队是LinkedBlockingQueue,表示若是当前线程数小于核心线程数,那么即便有空闲线程也不会复用线程去执行任务,而是建立新的线程去执行任务。若是当前执行任务数量大于核心线程数,此时再提交任务就在队列中等待,直到有可用线程。
用法:
public static void main(String[] args) { ExecutorService cachedThreadPool = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { final int index = i; try { Thread.sleep(index * 1000); } catch (InterruptedException e) { e.printStackTrace(); } cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread() + ":" + index); } }); } }
定义一个线程数为3的线程池,循环10次执行,能够发现运行的线程永远只有三个,结果以下:
Thread[pool-1-thread-1,5,main]:0 Thread[pool-1-thread-2,5,main]:1 Thread[pool-1-thread-3,5,main]:2 Thread[pool-1-thread-1,5,main]:3 Thread[pool-1-thread-2,5,main]:4 Thread[pool-1-thread-3,5,main]:5 Thread[pool-1-thread-1,5,main]:6 Thread[pool-1-thread-2,5,main]:7 Thread[pool-1-thread-3,5,main]:8 Thread[pool-1-thread-1,5,main]:9
源码:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
从源码就能够看出,该线程池基本就是只有一个线程数的newFixedThreadPool,它只有一个线程在工做,全部任务按照指定顺序执行。
用法:
和newFixedThreadPool相似,只是一直只有一个线程在工做,这里就不贴代码了。
源码:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
newScheduledThreadPool的方法不是直接返回一个ThreadPoolExecutor实例,而是经过有定时功能的ThreadPoolExecutor,也就是ScheduledThreadPoolExecutor
来返回ThreadPoolExecutor实例,从源码中能够看出:
一、该线程池能够设置核心线程数量,最大线程数与newCachedThreadPool同样,都是Integer.MAX_VALUE。
二、该线程池采用的队列是DelayedWorkQueue,具备延迟和定时的做用。
用法:
public static void main(String[] args) { ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); //延迟3秒执行,只执行一次 ((ScheduledExecutorService) scheduledThreadPool).schedule(new Runnable() { @Override public void run() { System.out.println("延迟========"); } },3,TimeUnit.SECONDS); //延迟1秒后每隔两秒执行一次 ((ScheduledExecutorService) scheduledThreadPool).scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("执行============"); } },1,2,TimeUnit.SECONDS); //单位是秒 }
四种线程池的使用就说到这里了,值得说明的是,除了上面的参数外,Executors类中还给这四种线程池提供了可传ThreadFactory
的重载方法,如下是它们的源码:
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory)); } public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); } public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
ThreadFactory是一个接口类,也就是咱们常常说的线程工厂,只有一个方法,能够用于建立线程:
Thread newThread(Runnable r);
默认状况下,ThreadPoolExecutor构造器传入的ThreadFactory
参数是Executors类中的defaultThreadFactory(),至关于一个线程工厂,帮咱们建立了线程池中所需的线程。在此我向你们推荐一个架构学习交流圈:830478757 帮助突破瓶颈 提高思惟能力
除此以外,咱们也能够自定义ThreadFactory,并根据本身的须要来操做线程,下面是实例代码:
public static void main(String[] args) { ExecutorService service = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); System.out.println("我是线程" + r); return t; } } ); //用lambda表达式编写方法体中的逻辑 Runnable run = () -> { try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "正在执行"); } catch (InterruptedException e) { e.printStackTrace(); } }; for (int i = 0; i < 5; i++) { service.submit(run); } //这里必定要作关闭 service.shutdown(); }
运行代码后,控制行会输出五行 “我是线程java.util.concurrent.ThreadPoolExecutor。。。。。”的信息,也证实了咱们自定义的ThreadFactory起到了做用。