# ThreadPool **Repository Path**: HackerX9/ThreadPool ## Basic Information - **Project Name**: ThreadPool - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-11-03 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ThreadPoolExecutor 首先通过线程池中线程的重用,减少创建和销毁线程的性能开销. 其次,能控制线程池中的并发数,否则会因为大量的线程争夺CPU资源造成阻塞. 最后,线程池能够对线程进行管理. ## ThreadPoolExecutor执行任务时的历程 备注:currentSize表示线程池中当前线程数量 1. 当currentSize=corePoolSize,并且workQueue未满时,添加进来的任务会被安排到workQueue中等待执行。 3. 当workQueue已满,但是currentSize=corePoolSize、workQueue已满、并且currentSize>maximumPoolSize时,调用handler默认抛出RejectExecutionExpection异常。 ## FixThreadPool ``` public static ExecutorService newFixThreadPool(int nThreads){ return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); } //使用 Executors.newFixThreadPool(5).execute(r); ``` FixThreadPool只有核心线程,并且数量固定的,也不会被回收,所有线程都活动时,因为队列没有限制大小,新任务会等待执行。 ## SingleThreadPool ``` public static ExecutorService newSingleThreadPool (int nThreads){ return new FinalizableDelegatedExecutorService ( new ThreadPoolExecutor (1, 1, 0, TimeUnit. MILLISECONDS, new LinkedBlockingQueue()) ); } //使用 Executors.newSingleThreadExecutor().execute(r); ``` SingleThreadPool只有一个核心线程,确保所有任务都在同一线程中按顺序完成。因此不需要处理线程同步的问题。 ## CachedThreadPool ``` public static ExecutorService newCachedThreadPool(int nThreads){ return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue()); } //使用 Executors.newCachedThreadPool().execute(r); ``` CachedThreadPool只有非核心线程,最大线程数非常大,所有线程都活动时,会为新任务创建新线程,否则利用空闲线程(60s空闲时间,过了就会被回收,所以线程池中有0个线程的可能)处理任务;任务队列SynchronousQueue相当于一个空集合,导致任何任务都会被立即执行。 ## ScheduledThreadPool ``` public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){ return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize){ super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedQueue ()); } //使用,延迟1秒执行,每隔2秒执行一次Runnable r Executors. newScheduledThreadPool (5).scheduleAtFixedRate(r, 1000, 2000, TimeUnit.MILLISECONDS); ``` 核心线程数固定,非核心线程(闲着没活干会被立即回收)数没有限制。