一些收藏Java多线程多线程java

线程池的使用以及实现原理

2019-12-18  本文已影响0人  降龙_伏虎

线程池优点

java中的线程池

        Executors.newFixedThreadPool(nThreads);//固定线程数线程池
        Executors.newCachedThreadPool();//有伸缩性线程池,线程60shou后回收
        Executors.newSingleThreadExecutor();//只有一个核心线程的线程池
        Executors.newSingleThreadScheduledExecutor();//定时任务线程池
        Executors.newWorkStealingPool();//fork/join线程池
    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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, //核心线程数=传入线程数
                                      nThreads,//最大线程数=传入线程数
                                      0L,//超时间=0
                                      TimeUnit.MILLISECONDS,//超时时间单位=秒
                                      new LinkedBlockingQueue<Runnable>()//双向链表阻塞队列
);
    }
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(
                                      0, //核心线程数=0
                                      Integer.MAX_VALUE,//最大线程数=Integer最大值(可当做无限大)
                                      60L, //超时时间=60
                                      TimeUnit.SECONDS,//超时时间单位=秒
                                      new SynchronousQueue<Runnable>()//不存储元素的阻塞队列
);
    }
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 核心线程数=1
                                    1,//最大线程数=1
                                    0L,//超时时间0     
                                    TimeUnit.MILLISECONDS,//超时时间单位:毫秒
                                    new LinkedBlockingQueue<Runnable>()//双向链表阻塞队列
));
    }

执行流程图

image.png

问题

上一篇下一篇

猜你喜欢

热点阅读