zoukankan      html  css  js  c++  java
  • 线程池

    一、线程池介绍

    1.1 为什么使用线程池

    使用多线程技术可以并行的执行任务,从时间效率来看提升很大。但是频繁的创建和销毁线程,对系统资源的消耗很大,为了防止资源不足,需要一些办法来限制指定时间处理的请求数目。

    线程池为线程生命周期开销问题和资源不足问题提供了解决方案。通过对多个任务重用线程,线程创建的开销被分摊到了多个任务上。其好处是,因为在请求到达时线程已经存在,所以无意中也消除了线程创建所带来的延迟。这样,就可以立即为请求服务,使应用程序响应更快。而且,通过适当地调整线程池中的线程数目,也就是当请求的数目超过某个阈值时,就强制其它任何新到的请求一直等待,直到获得一个线程来处理为止,从而可以防止资源不足。

    1.2 线程池执行流程

    二、线程池的使用

    2.1 创建线程池

    线程池的实现类是 ThreadPoolExecutor ,构造方法如下:

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
     
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }
     
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }
     
    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;
    }
    

    可以看到,其需要如下几个参数:

    • corePoolSize(必需):核心线程数。默认情况下,核心线程会一直存活,但是当将allowCoreThreadTimeout 设置为 true 时,核心线程也会超时回收。
    • maximumPoolSize(必需):线程池所能容纳的最大线程数。当活跃线程数达到该数值后,后续的新任务将会阻塞。
    • keepAliveTime(必需):线程闲置超时时长。如果超过该时长,非核心线程就会被回收。如果将allowCoreThreadTimeout设置为true时,核心线程也会超时回收。
    • unit(必需):指定keepAliveTime参数的时间单位。常用的有:TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)、TimeUnit.MINUTES(分)。
    • workQueue(必需):任务队列。通过线程池的 execute()方法提交的 Runnable 对象将存储在该参数中。其采用阻塞队列实现。
    • threadFactory(可选):线程工厂。用于指定为线程池创建新线程的方式。
    • handler(可选):拒绝策略。当达到最大线程数时需要执行的饱和策略。

    2.2 线程池使用实例

    public class CreateDemo {
    
        public static void main(String[] args) {
            int corePoolSize = 10;
            int maximumPoolSize = 100;
            long keepAliveTime = 100;
            BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque();
            // 创建线程池
            ThreadPoolExecutor poolExecutor =
                    new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
            // 向线程池中添加任务
            poolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
            // 关闭线程池
            poolExecutor.shutdown(); // 设置线程池的状态为SHUTDOWN,然后中断所有没有正在执行任务的线程
            poolExecutor.shutdownNow(); // 设置线程池的状态为 STOP,然后尝试停止所有的正在执行或暂停任务的线程,并返回等待执行任务的列表
        }
    
    }
    

    三、线程池核心参数

    3.1 任务队列(workQueue)

    任务队列是基于阻塞队列实现的,即采用生产者消费者模式,需要实现 BlockingQueue接口,我们来看下接口定义:

    public interface BlockingQueue<E> extends Queue<E> {
        boolean add(E e);
        boolean offer(E e);    
        void put(E e) throws InterruptedException;  
        boolean offer(E e, long timeout, TimeUnit unit)
            throws InterruptedException;
        E take() throws InterruptedException;
        E poll(long timeout, TimeUnit unit)
            throws InterruptedException;
        int remainingCapacity();
        boolean remove(Object o);
        public boolean contains(Object o);
        int drainTo(Collection<? super E> c);
        int drainTo(Collection<? super E> c, int maxElements);    
    }
    

    Java 已经为我们提供了一些阻塞队列的实现:

    • ArrayBlockingQueue:一个由数组结构组成的有界阻塞队列(数组结构可配合指针实现一个环形队列)。
    • LinkedBlockingQueue: 一个由链表结构组成的有界阻塞队列,在未指明容量时,容量默认为Integer.MAX_VALUE
    • PriorityBlockingQueue: 一个支持优先级排序的无界阻塞队列,对元素没有要求,可以实现Comparable 接口也可以提供 Comparator 来对队列中的元素进行比较。跟时间没有任何关系,仅仅是按照优先级取任务。
    • DelayQueue:类似于PriorityBlockingQueue,是二叉堆实现的无界优先级阻塞队列。要求元素都实现Delayed 接口,通过执行时延从队列中提取任务,时间没到任务取不出来。
    • SynchronousQueue: 一个不存储元素的阻塞队列,消费者线程调用 take() 方法的时候就会发生阻塞,直到有一个生产者线程生产了一个元素,消费者线程就可以拿到这个元素并返回;生产者线程调用 put() 方法的时候也会发生阻塞,直到有一个消费者线程消费了一个元素,生产者才会返回。
    • LinkedBlockingDeque: 使用双向队列实现的有界双端阻塞队列。双端意味着可以像普通队列一样FIFO(先进先出),也可以像栈一样 FILO(先进后出)。
    • LinkedTransferQueue: 它是ConcurrentLinkedQueueLinkedBlockingQueueSynchronousQueue 的结合体,但是把它用在 ThreadPoolExecutor 中,和 LinkedBlockingQueue行为一致,但是是无界的阻塞队列。

    有界队列和无界队列的区别: 如果使用有界队列,当队列饱和时并超过最大线程数时就会执行拒绝策略;而如果使用无界队列,因为任务队列永远都可以添加任务,所以设置 maximumPoolSize 没有任何意义。

    3.2 线程工厂(threadFactory)

    线程工厂指定创建线程的方式,需要实现 ThreadFactory 接口,并实现 Thread newThread(Runnable r) 方法。该参数可以不用指定,Executors 框架已经为我们实现了一个默认的线程工厂:

    private static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;
     
        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }
     
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
    

    3.3 拒绝策略(handler)

    当线程池的线程数达到最大线程数时,需要执行拒绝策略。拒绝策略需要实现 RejectedExecutionHandler接口,并实现 rejectedExecution(Runnable r, ThreadPoolExecutor executor)方法。 Executors 框架也为我们实现了四种拒绝策略:

    • AbortPolicy(默认):丢弃任务并抛出 RejectedExecutionException 异常。

    • CallerRunsPolicy:由调用线程自行处理该任务。

    • DiscardPolicy:丢弃任务,但是不抛出异常。可以配合这种模式进行自定义的处理方式。

    • DiscardOldestPolicy:丢弃队列最早的未处理任务,然后重新尝试执行任务。

    四、功能线程池

    Executors 为了方便我们的使用,已经为我们封装好了四种常见的功能线程池:

    • 定长线程池(FixedThreadPool)
    • 定时线程池(ScheduledThreadPool )
    • 可缓存线程池(CachedThreadPool)
    • 单线程化线程池(SingleThreadExecutor)

    4.1 定长线程池(FixedThreadPool)

    构造函数:

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
    
    • 特点:只有核心线程,线程数量固定,执行完立即回收,任务队列为链表结构的有界队列。
    • 应用场景:控制线程最大并发数。

    4.2 定时线程池(ScheduledThreadPool )

    构造函数:

    private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
     
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }
     
    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }
    
    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue(), threadFactory);
    
    
    • 特点:核心线程数量固定,非核心线程数量无限,执行完闲置10ms后回收,任务队列为延时阻塞队列。
    • 应用场景:执行定时或周期性的任务。

    4.3 可缓存线程池(CachedThreadPool)

    构造函数:

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
    
    
    • 特点:无核心线程,非核心线程数量无限,执行完闲置60s后回收,任务队列为不存储元素的阻塞队列。
    • 应用场景:执行大量、耗时少的任务。

    4.4 单线程化线程池(SingleThreadExecutor)

    构造函数:

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }
    
    • 特点:只有1个核心线程,无非核心线程,执行完立即回收,任务队列为链表结构的有界队列。
    • 应用场景:不适合并发但可能引起IO阻塞性及影响UI线程响应的操作,如数据库操作、文件操作等。

    4.5 ExecutorService

    以上四个线程池返回的都是 ExecutorService 对象,我们来看下它的方法:

    修饰符和类型 方法和说明
    boolean awaitTermination(long timeout, TimeUnit unit)阻塞,直到关闭请求后所有任务完成执行,发生超时或当前线程中断(以先发生者为准)为止。
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)执行给定的任务,并在所有任务完成时返回保存其状态和结果的期货列表。
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)执行给定的任务,并在所有完成或超时到期时(以先发生者为准)返回持有其状态和结果的期货列表。
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)执行给定的任务,返回成功完成的任务的结果(即没有引发异常)(如果有的话)。
    <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)执行给定的任务,如果在给定的超时时间过去之前完成任务,则返回已成功完成任务的结果(即,不引发异常)。
    boolean isShutdown()返回true此执行器是否已关闭。
    boolean isTerminated()返回true所有任务在关闭后是否已完成。
    void shutdown()启动有序关闭,在该关闭中执行先前提交的任务,但不接受任何新任务。
    List<Runnable> shutdownNow()尝试停止所有正在执行的任务,暂停正在等待的任务的处理,并返回正在等待执行的任务的列表。
    <T> Future<T> submit(Callable<T> task)提交要执行的返回值任务,并返回表示任务的未决结果的Future。
    Future<?> submit(Runnable task)提交一个Runnable任务以执行并返回一个表示该任务的Future。
    <T> Future<T> submit(Runnable task, T result)提交一个Runnable任务以执行并返回一个表示该任务的Future。

    使用实例:

        public static void main(String[] args) throws ExecutionException, InterruptedException {
            final ExecutorService notReturnValueExecutorService = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 100; i++) {
                int finalI = i;
                notReturnValueExecutorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "正在执行第" + finalI + "个任务");
                    }
                });
            }
            // 关闭线程池
            notReturnValueExecutorService.shutdown();
    
    
            final ExecutorService hasReturnValueExecutorService = Executors.newFixedThreadPool(10);
            List<Future<String>> futureList = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                final Future<String> result = hasReturnValueExecutorService.submit(
                        new Callable<String>() {
                            @Override
                            public String call() throws Exception {
                                String result = Thread.currentThread().getName() + "生成随机数:" + new Random().nextInt();
                                Thread.sleep(500);
                                return result;
                            }
                        });
                futureList.add(result);
            }
            hasReturnValueExecutorService.shutdown();
            for (Future<String> future: futureList){
                System.out.println(future.get());
            }
        }
    

    4.6 使用建议

    虽然这四个功能线程池虽然方便,但建议最好直接通过使用 ThreadPoolExecutor 的方式,这样的处理方式让使用者能更加明确线程池的运行规则,规避资源耗尽的风险。

    Executors 的四个功能线程分别有如下弊端:

    • FixedThreadPoolSingleThreadExecutor:主要问题是堆积的请求处理队列均采用LinkedBlockingQueue,可能会耗费非常大的内存,甚至 OOM。
    • CachedThreadPoolScheduledThreadPool:主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至 OOM。
  • 相关阅读:
    javascript 使用链式结构
    javascript 闭包
    javascript 使用canvas绘画
    (14)javascript 函数表达式 递归、闭包
    (13)javascript 面向对象 创建对象
    wpf和winform的区别
    XtraReport1添加参数
    {$DEFINE WANYI}
    $('#myModal').modal('show') //显示$('#myModal').modal('hide')隐藏
    计算机音视频技术
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/13850277.html
Copyright © 2011-2022 走看看