Executors创建线程池的正确方法及源码分析

tech2022-08-03  144

java.util.concurrent.ExecutorService; java.util.concurrent.Executors; 这两个包可以用来创建线程池,具体的方法如下:

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //Excutors 工具类、3大方法 public class ThreadPoolTest { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); //单个线程 // ExecutorService threadPool = Executors.newFixedThreadPool(5); //固定大小的线程池 // ExecutorService threadPool = Executors.newCachedThreadPool(); //可变大小的线程池 try { for (int i=0;i<100;i++){ threadPool.execute(()->{ System.out.println(Thread.currentThread().getName()+" ok"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } } public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }

这三个方法底层都调用了以下方法:

public ThreadPoolExecutor(int corePoolSize,//核心线程池的大小 int maximumPoolSize, //最大核心线程池大小 long keepAliveTime, //超时释放时间 TimeUnit unit,//超时释放单位 BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

正确的写法为:

import java.util.concurrent.*; //Excutors 工具类、3大方法 public class ThreadPoolTest { public static void main(String[] args) { // ExecutorService threadPool = Executors.newSingleThreadExecutor(); //单个线程 // ExecutorService threadPool = Executors.newFixedThreadPool(5); //固定大小的线程池 // ExecutorService threadPool = Executors.newCachedThreadPool(); //可变大小的线程池 ExecutorService threadPool =new ThreadPoolExecutor( 2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy() ); try { //最大承载数 = maximunPoolSize+ Deque capacity for (int i=0;i<9;i++){ threadPool.execute(()->{ System.out.println(Thread.currentThread().getName()+" ok"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } }
最新回复(0)