线程池,3大方法,7大参数,4种拒绝策略

线程池的技术:

事先准备好一些资源,有人要用就来拿,用完记得还(关闭池)

线程池的好处

  1. 减少资源的消耗
  2. 提高系统的性能,提高相应速度(因为池的开启和关闭非常消耗资源)
  3. 易于一起管理线程

总结:线程池的优点:线程复用,可以控制最大并发数,管理线程

三大方法


    public static void main(String[] args) {
        //ExecutorService ThreadPool = Executors.newSingleThreadExecutor();//单个线程启动
        //ExecutorService ThreadPool = Executors.newFixedThreadPool(9);//自定义线程的大小
        ExecutorService ThreadPool = Executors.newCachedThreadPool();//根据运行的任务,可伸缩创建线程大小,任务越重,线程就越多,任务越轻,线程越少
        try {
            for (int i = 0; i < 10; i++) {
                ThreadPool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"");
                });
            }
        } finally {
            ThreadPool.shutdown();//用完就要关闭线程池
        }
    }

七大参数

ThreadPoolExecutor(int corePoolSize,//主要线程大小
int maximumPoolSize,//最大线程大小
long keepAliveTime,//存在时间,没有线程使用这个线程池,超过这个时间就会销毁池
TimeUnit unit,//时间单位
BlockingQueue<Runnable> workQueue//阻塞队列
ThreadFactory threadFactory,//线程工厂,一般是默认的,固定的
RejectedExecutionHandler handler//拒绝策略(有四种)
)

我们自定义一个线程池,来说明七大参数

package com.luoKing.ThreadPool;

import java.util.concurrent.*;

public class poolMothed {

    public static void main(String[] args) {
        ThreadPoolExecutor ThreadPool= new ThreadPoolExecutor(2,
                5,
                3,
                TimeUnit.DAYS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());



        try {
            for (int i = 0; i < 10; i++) {
                ThreadPool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"");
                });
            }
        } finally {
            ThreadPool.shutdown();//用完就要关闭线程池
        }
    }
}

四大拒绝策略

/*
*
* new ThreadPoolExecutor.AbortPolicy()//超过线程池最大容量(MAXPool+capacity),就会抛出异常
*new ThreadPoolExecutor.CallerRunsPolicy()//当超过最大容量时,还有线程进入,那么就会返回到原来的地方(从哪来就返回到哪里去)
*new ThreadPoolExecutor.DiscardPolicy()//会直接丢弃线程,不处理
* new ThreadPoolExecutor.DiscardOldestPolicy()//等待最早的线程,如果最早的线程处理完,就接受该线程,否则丢弃
* */

拓展

线程池的最大线程数大小如何确定?

  1. CPU密集型:你电脑有多少核数,最大线程就设置为多少(一般如下编写)
Runtime.getRuntime().availableProcessors(),//获取当前计算机的最大核数
  1. IO密集型:由于IO的读写十分消耗资源,为了提高运行速度,我们可以将线程数量调为IO线程数量的两倍
posted @ 2022-05-07 11:15  小罗要有出息  阅读(226)  评论(0编辑  收藏  举报