java线程池

2020-04-12  本文已影响0人  Darker_c772

线程池的概念

简单来说线程池就是一个管理线程的池子,当我们有任务需要执行无需创建线程,只需要将任务提交到线程池即可。

线程池的优点

线程池的创建

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }

核心参数的作用

线程池运行过程

线程池运行过程

拒绝策略

JUC下的线程池

固定长度线程池

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

特点

工作机制

线程池运行过程

可缓存线程的线程池

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

特点

工作机制

线程池运行过程

单线程的线程池

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

特点

工作机制

线程池运行过程

定时及周期执行的线程池

    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

特点

Java线程池配置原则

任务类型

实例

public class ThreadPoolUtil {
    
    /**
     * 创建的线程设置有意义的名字,可方便排查问题。
     */
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build();
    /**
     * 建议阻塞队列使用有界队列,既可以保证不会因为任务挤压导致系统崩溃,
     * 同时也有助于我们及时的发现问题,作出响应(例如当阻塞队列满时预警)。
     * 阻塞队列的最大值可根据实际业务场景自行设置
     */
    private  static ExecutorService executorService= new ThreadPoolExecutor(ioIntesivePoolSize(), ioIntesivePoolSize(),
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(100),namedThreadFactory,new ThreadPoolExecutor.AbortPolicy());


    private ThreadPoolUtil() {

    }

    public static void exec(Runnable runnable){
        executorService.execute(runnable);
    }

    public static void submit(Callable callable){
        executorService.submit(callable);
    }
    /**
     * Each tasks blocks 90% of the time, and works only 10% of its
     *  lifetime. That is, I/O intensive pool
     * @return io密集的线程池
     */
    public static int ioIntesivePoolSize() {

        double blockingCoefficient = 0.9;
        return poolSize(blockingCoefficient);
    }


    /**
     * A computation-intensive task has a blocking coefficient of 0
     * @return cpu intesive Thread pool size
     */
    public static int cpuIntesivePoolSize() {

        double blockingCoefficient = 1;
        return poolSize(blockingCoefficient);
    }

    /**
     *
     * Number of threads = Number of Available Cores / (1 - Blocking
     * Coefficient) where the blocking coefficient is between 0 and 1.
     *
     * A computation-intensive task has a blocking coefficient of 0, whereas an
     * IO-intensive task has a value close to 1,
     * so we don't have to worry about the value reaching 1.
     *  @param blockingCoefficient the coefficient
     *  @return Thread pool size
     */
    public static int poolSize(double blockingCoefficient) {
        int numberOfCores = Runtime.getRuntime().availableProcessors();
        int poolSize = (int) (numberOfCores / (1 - blockingCoefficient));
        return poolSize;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读