多线程之使用线程池创建线程

1.使用线程池的优点

1.减少资源的消耗。重复利用已经创建的线程,避免频繁的创造和销毁线程,减少消耗。

2.提高响应速度。当执行任务时,不需要去创建线程再来执行,只要调动现有的线程来执行即可。

3.提高了线程的管理性。线程是稀缺资源,使用线程池可以进行统一的分配、调优和监控。

2.创建线程池的两种方案

1.通过Executors创建,它提供了四种线程池:

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

注意:不建议使用这种方法创建线程池。因为newFixedThreadPool 和newSingleThreadExecutor允许的最大请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。newCachedThreadPoo和newScheduledThreadPool允许的创建线程的最大数量为Integer.MAX_VALUE,,从而导致OOM。

public class Demo01 {
    public static void main(String[] args) {
        //ExecutorService threadPool = Executors.newSingleThreadExecutor(); //创建单个线程
        //ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);//创建一个固定大小的线程池
        //ExecutorService threadPool = Executors.newFixedThreadPool(5); //创建一个固定大小的线程池
        ExecutorService threadPool = Executors.newCachedThreadPool(); //创建大小可伸缩的线程池

        try {
            for (int i = 0; i < 30; i++) {
                //使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown(); //线程池使用完毕后需要关闭
        }

    }
}

2.通过ThreadPoolExecutor创建,new ThreadPoolExecutor有7个核心参数,分别如下:

ThreadPoolExecutor(int corePoolSize, //核心线程池大小,始终存在
               int maximumPoolSize, //最大线程数
                long keepAliveTime, //空闲线程等待时间,超时则销毁
                     TimeUnit unit, //时间单位
 BlockingQueue<Runnable> workQueue, //等待阻塞队列
       ThreadFactory threadFactory, //线程工厂
   RejectedExecutionHandler handler) //线程拒绝策略

其最后一个参数拒绝策略共有四种:

//new ThreadPoolExecutor.AbortPolicy():达到最大承载量,不再处理,并且抛出异常
//new ThreadPoolExecutor.CallerRunsPolicy():达到最大承载量,从哪来的去哪里
//new ThreadPoolExecutor.DiscardPolicy():达到最大承载量,丢掉任务,但不抛出异常
//new ThreadPoolExecutor.DiscardOldestPolicy():达到最大承载量,尝试与最早执行的线程去竞争,不抛出异常
public class Demo02 {
    public static void main(String[] args) {
        //new ThreadPoolExecutor.AbortPolicy():达到最大承载量,不再处理,并且抛出异常
        //new ThreadPoolExecutor.CallerRunsPolicy():达到最大承载量,从哪来的去哪里
        //new ThreadPoolExecutor.DiscardPolicy():达到最大承载量,丢掉任务,但不抛出异常
        //new ThreadPoolExecutor.DiscardOldestPolicy():达到最大承载量,尝试与最早执行的线程去竞争,不抛出异常

        //最大线程池大小该如何定义
        //1.cpu密集型,逻辑处理器个数
        //2.io密集型 > 判断程序十分耗IO的线程,最大线程池大小应该比这个大
        int maxPools= Runtime.getRuntime().availableProcessors();
        System.out.println(maxPools);

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                maxPools,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        try {
            for (int i = 0; i < 10; i++) {
                //使用线程池来创建线程
                //最大承载:maximumPoolSize+workQueue,超过执行拒绝策略
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown(); //线程池使用完毕后需要关闭
        }

    }
}
  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值