JUC(五) 线程池

线程池
 

池化技术及线程池的使用

程序的运行,本质:占用系统的资源!优化资源的使用
线程池,连接池,内存池,对象池
池化技术:事先准备好一些资源,有人要用就来拿,用完之后归还

线程池的好处

1.降低资源的消耗
2.提高响应速度
3.方便管理

线程可以复用,可以控制最大并发量,管理线程
线程池:三大方法,7大参数,4种拒绝策略
线程的三大方法

        线程池不建议使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式更加明确线程池的运行规则,规避资源耗尽的风险。

说明:Executors各个方法的弊端:
1)newFixedThreadPool和newSingleThreadExecutor:
主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。
2)newCachedThreadPool和newScheduledThreadPool:
主要问题是线程数最大数是Integer.MAX_VALUE(约为21亿),可能会创建数量非常多的线程,甚至OOM。

Executors 工具类 3大方法

不建议使用,建议自定义

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

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

源码分析及7大参数

假设去银行办理业务,一开始有2个窗口(核心线程),2个窗口人满了,进来的人就会到候客区(阻塞队列),当候客区的人满了就会开启多的线程(线程总数只能开到max),如果线程数到最大,候客区(阻塞队列)也满了,再进来的人就会被拒绝(拒绝策略)

 

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}



public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}



public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

本质:new ThreadPoolExecutor()

int corePoolSize                              //核心线程池大小              (正常大小)
int maximumPoolSize                     //最大核心线程池大小   (需要时才会开启,队列满了触发)
long keepAliveTime                        //超时了没有人调用就会释放 
TimeUnit unit                                              //超时单位  
BlockingQueue<Runnable> workQueue    //阻塞队列    (排队人数)
ThreadFactory threadFactory                    //线程工厂,创建线程的,一般不用动
RejectedExecutionHandler handler           //拒绝策略        (队列满了拒绝)

 

4种拒绝策略

//                    银行满了还有人进来,不处理这个人,抛出异常
//                new ThreadPoolExecutor.AbortPolicy()

//                    哪里来的去哪里
//                new ThreadPoolExecutor.CallerRunsPolicy()
//                    队列满了不会抛出异常,丢掉任务
//                new ThreadPoolExecutor.DiscardPolicy()
//                    队列满了,尝试去和最早得竞争,也不会抛出异常
//                new ThreadPoolExecutor.DiscardOldestPolicy()

public ThreadPoolExecutor(int corePoolSize, //核心线程池大小
                              int maximumPoolSize, //最大核心线程池大小
                              long keepAliveTime, //超时了没有人调用就会释放
                              TimeUnit unit, //超时单位
                              BlockingQueue<Runnable> workQueue, //阻塞队列
                              ThreadFactory threadFactory, //线程工厂,创建线程的,一般不用动
                              RejectedExecutionHandler handler) { //拒绝策略
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

自定义线程池(建议)

建议使用自定义

public static void main(String[] args) {
        //Executors工具类,三大方法
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定大小得线程池
//        ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩,线程数可变
        //自定义线程池,工作
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
//                    银行满了还有人进来,不处理这个人,抛出异常
//                new ThreadPoolExecutor.AbortPolicy()
//                    队列满了不会抛出异常,丢掉任务
//                new ThreadPoolExecutor.DiscardPolicy()
//                    哪里来的去哪里
//                new ThreadPoolExecutor.CallerRunsPolicy()
//                    队列满了,尝试去和最早得竞争,也不会抛出异常
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        //最大承载:队列+max值
        for (int i = 0; i < 8; i++) {
            //使用了线程池之后,使用线程池来创建线程
            threadPoolExecutor.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
            });
        }
        //线程池用完,程序结束,关闭线程池
        try {
            threadPoolExecutor.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

最大线程池应该如何定义


1.cpu密集行:几核就是几,可以保持CPU的效率最高!
你的电脑是几核心的(用程序获取)你的最大线程数就设成几,可以保持CPU的效率最高)
2.io密集型:最大线程数 > 判断你程序中十分耗IO的线程
例如:你的程序里面有15个任务很占用IO资源,就用15个线程去执行,所以最大
线程数量大于这个15就好了,一般是大型IO任务数量的2倍


System.out.println(Runtime.getRuntime().availableProcessors());//获得cpu的核心数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值