java--线程池

本文介绍了Java中的线程池概念,重点讨论了ExecutorService的三大常见创建方法(固定、单线程和缓存线程池),以及ThreadPoolExecutor的构造函数参数和四种拒绝策略。作者强调了如何根据任务类型合理设置最大线程数,以优化性能。
摘要由CSDN通过智能技术生成

线程池的好处:

降低资源的消耗

提高响应的速度

方便管理

线程复用,可以控制最大并发数,管理线程

Executors 三大方法

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(),
                                  threadFactory);
}
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,//21亿
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
package org.example;


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

/**
 * Executors 工具类三大方法
 *
 */
public class Demo01 {
    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
//        Executors.newFixedThreadPool(5);//创建一个固定的线程池大小
        ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩的,遇强则强 ,遇弱则弱
//
        try{
            for (int i = 0; i < 1000; i++) {
                //使用了线程池之后,使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }
    }
}

本质ThreadPoolExecutor()

七大参数

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;
}

建议使用ThreadPoolExecutor,了解线程池的原理

package org.example;


import java.util.concurrent.*;

/**
 * Executors 工具类三大方法
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy()//银行满了,还有人进来,不处理 这个人的,抛出异常
//                new ThreadPoolExecutor.CallerRunsPolicy()//哪来的去哪里
//                new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常
                new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试和最早的竞争

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

四种拒绝策略

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

new ThreadPoolExecutor.CallerRunsPolicy()//哪来的去哪里 

new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常

new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试和最早的竞争

最大线程到底该如何定义
1.cpu密集型 几核 就是几个,可以保持cpu的效率最高
2.IO 密集型   >判断你程序中十分耗IO的线程
      程序 15个大型任务,io十分占用资源
//获取cpu核数
System.out.println(Runtime.getRuntime().availableProcessors());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值