Java多线程(27)——JUC——线程池excutors系列(2)——ThreadPoolExcutor(1)——创建线程池的底层原理

目录

1.概述

2.Excutors创建线程池的6种方式

2.1 Excutors.newFixedThreadPool(int)

(1)使用案例

(2)源码及特点

2.2 Excutors.newSingleThreadExecutor(int)

(1)使用案例

(2)源码及特点

2.3 Excutors.newCachedThreadPool(int)

(1)使用案例

(2)源码及特点

2.4 Excutors.newScheduledThreadPool(int)

2.5 Excutors.newSingleThreadScheduledExecutor(int)

2.6 Excutors.newWorkStealingPool(int)

3.ThreadPoolExecutor的7大参数

4.线程池的底层工作原理

5.线程池的4大拒绝策略

6.实际工作中使用哪一个线程池?——自定义线程池

6.1 自定义线程池(即自己传入参数来new ThreadPoolExcutor)使用案例

6.2 如何合理配置的线程数?

(1)CPU密集型

(2)IO密集型


1.概述

ThreadPoolExecutor 是线程池的核心实现

2.Excutors创建线程池的6种方式

2.1 Excutors.newFixedThreadPool(int)

  • 创建固定线程数的线程池

(1)使用案例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个池5个线程

        //模拟10个用户来办理业务,每个用户就是来自于外部的请求线程

        try {

            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}

  • 可以发现只有5个线程被复用去处理业务

(2)源码及特点

主要特点:

  • 1.创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列种等待
  • 2.创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的是LinkedBlockingQueue

2.2 Excutors.newSingleThreadExecutor(int)

  • 创建只有一个线程的线程池

(1)使用案例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个池1个线程

        //模拟10个用户来办理业务,每个用户就是来自于外部的请求线程

        try {

            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}

  • 可以发现只有一个线程处理任务

(2)源码及特点

主要特点:

  • 1.创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行
  • 2.创建的线程池corePoolSize和maximumPoolSize值都设置为1,它使用的是LinkedBlockingQueue

注意

  • newFixedThreadPool(1,threadFactory) 不等价于 newSingleThreadExecutor
    • newSingleThreadExecutor创建的线程池保证内部只有一个线程执行任务,并且线程数不可扩展
    • 而通过newFi
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值