美文网首页
14Java线程池的底层实现与使用

14Java线程池的底层实现与使用

作者: 滔滔逐浪 | 来源:发表于2020-07-08 20:31 被阅读0次

    在我们进行开发的时候,为了充分利用系统资源,我们通常会进行多线程开发,实现起来非常简单,需要使用线程的时候就去创建一个线程(继承Thread类、实现Runnable接口、使用Callable和Future),但是这样也有一点问题,就是如果并发的线程数量很多,创建线程、销毁线程都是需要消耗时间、资源,这个时候线程池就派上用场了

    Java通过Executors提供了四种线程池,分别是

    1.newSingleThreadExecutor()

    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务都是按照指定的顺序(FIFO,LIFO,优先级)执行

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

    2.newFixedThreadExecutor()

    创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

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

    3.newCachedThreadPool()

    创建一个可缓存的线程池,如果当前没有可用线程,在执行结束后缓存60s,如果不被调用则移除线程。调用execute()方法时可以重用缓存中的线程。适用于很多短期异步任务的环境,可以提高程序性能。

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

      4.newScheduledThreadPool()(在ScheduleThreadPoolExecutor类中,ThreadPoolExecutor的子类)

    创建一个定长线程池,支持定时及周期性任务执行

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

    二、线程池的底层类与接口
      在介绍线程池的实现机制之前,先了解一下线程池重要的类或接口

    ExecutorService是真正的线程池接口

    Executors是静态工厂的功能,生产各种类型线程池

    Executor是线程池的顶级接口,只是一个执行线程的工具,只提供一个execute(Runnable command)的方法,真正的线程池接口是ExecutorService

    AbstractExecutorService实现了ExecutorService接口,实现了其中大部分的方法(有没有实现的方法,所以被声明为Abstract)

    ThreadPoolExecutor,继承了AbstractExecutorService,是ExecutorService的默认实现

    相关文章

      网友评论

          本文标题:14Java线程池的底层实现与使用

          本文链接:https://www.haomeiwen.com/subject/kzehcktx.html