JUC(一)——Locks
JUC(二)——深入理解锁机制
JUC(三)——线程安全类
JUC(四)——强大的辅助类讲解
JUC(五)——Callable
JUC(六)——阻塞队列
JUC(七)——线程池简单使用
JUC(八)——线程池深入讲解
为什么使用线程池?
-
例子:
- 10年前单核CPU电脑,假的多线程,像马戏团小丑玩多个球,CPU需要来回切换。
现在是多核电脑,多个线程各自跑在独立的CPU上,不用切换效率高。
- 10年前单核CPU电脑,假的多线程,像马戏团小丑玩多个球,CPU需要来回切换。
-
线程池的优势:
- 线程池做的工作只要是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。
-
它的主要特点为:
- 线程复用
- 控制最大并发数
- 管理线程
-
优点:
- 第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的销耗。
- 第二:提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立即执行。
- 第三:提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会销耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
-
Java中的线程池是通过Executor框架实现的,该框架中用到了Executor,Executors,ExecutorService,ThreadPoolExecutor这几个类

Executors
- newFixedThreadPool():自己指定线程数
- 构造器
-
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
-
- 代码实例
-
public class MyThreadPoolDemo { public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池5线程 // 一个银行已经new好了5个受理窗口,有5个工作人员。 try { //一池5个工作人员(银行受理窗口),模拟20个客户(request)来银行实体店办理业务。 for (int i = 1; i <=12; i++) { final int tempI = i; threadPool.execute(() -> {System.out.println(Thread.currentThread().getName()+"\t 受理业务"+"\t 客户号:"+tempI);}); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
-
- 构造器
- newSingleThreadExecutor():只有一个线程
- 构造器
-
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
-
- 代码实例
-
public class MyThreadPoolDemo { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1线程 // 一个银行已经new好了1个受理窗口,有1个工作人员。 try { //一池1个工作人员(银行受理窗口),模拟20个客户(request)来银行实体店办理业务。 for (int i = 1; i <=12; i++) { final int tempI = i; threadPool.execute(() -> {System.out.println(Thread.currentThread().getName()+"\t 受理业务"+"\t 客户号:"+tempI);}); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
-
- 构造器
- newCachedThreadPool():0-N个线程
- 构造器
-
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
-
- 代码实例
-
public class MyThreadPoolDemo { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1线程 // 一个银行已经new好了1个受理窗口,有1个工作人员。 try { //一池1个工作人员(银行受理窗口),模拟20个客户(request)来银行实体店办理业务。 for (int i = 1; i <=12; i++) { final int tempI = i; threadPool.execute(() -> {System.out.println(Thread.currentThread().getName()+"\t 受理业务"+"\t 客户号:"+tempI);}); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
-
- 构造器
Java线程池精讲
本文深入探讨Java线程池的原理与应用,包括线程池如何控制线程数量、提高资源利用效率和响应速度,以及如何通过Executor框架实现线程池。文中详细介绍了固定线程数、单一线程和缓存线程池的创建与使用,通过实例展示线程池在处理大量任务时的优势。
1132

被折叠的 条评论
为什么被折叠?



