zoukankan      html  css  js  c++  java
  • 并发编程-concurrent指南-线程池ExecutorService的实例

    1、new Thread的弊端

    执行一个异步任务你还只是如下new Thread吗?

    new Thread(new Runnable() {
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
        }
    }).start();

    那你就out太多了,new Thread的弊端如下:
    a. 每次new Thread新建对象性能差。
    b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
    c. 缺乏更多功能,如定时执行、定期执行、线程中断。
    相比new Thread,Java提供的四种线程池的好处在于:
    a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
    b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
    c. 提供定时执行、定期执行、单线程、并发数控制等功能。

    Java通过Executors提供四种线程池,分别为:

    newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

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

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

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

    1.CachedThreadPool

    创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程

    public class ThreadRunner implements Runnable{
        private int num;
       private int timeout;
    public ThreadRunner(int num,int timeout){ this.num = num;
    this.timeout = timeout; } @Override
    public void run() { System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
    try {
        TimeUnit.SECONDS.sleep(timeout);
         } catch (InterruptedException e) {
        e.printStackTrace();
         }
    } }
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class CacheThreadPoolMain {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newCachedThreadPool();
            for(int i = 1;i<21;i++){
                pool.submit(new ThreadRunner(i,0));
            }
            pool.shutdown();
        }
    }

    结果:

    pool-1-thread-1:运行中,1
    pool-1-thread-5:运行中,5
    pool-1-thread-2:运行中,2
    pool-1-thread-7:运行中,7
    pool-1-thread-4:运行中,4
    pool-1-thread-9:运行中,9
    pool-1-thread-3:运行中,3
    pool-1-thread-10:运行中,10
    pool-1-thread-8:运行中,8
    pool-1-thread-6:运行中,6
    pool-1-thread-12:运行中,12
    pool-1-thread-11:运行中,11
    pool-1-thread-13:运行中,13
    pool-1-thread-9:运行中,14
    pool-1-thread-10:运行中,20
    pool-1-thread-13:运行中,15
    pool-1-thread-8:运行中,19
    pool-1-thread-11:运行中,16
    pool-1-thread-6:运行中,18
    pool-1-thread-12:运行中,17

    总结
    - 池中线程时随着处理数据增加而增加
    - 线程数并不是一直增加,如果有新任务需要执行时,首先查询池中是否有空闲线程并且还为到空闲截止时间,如果有,则使用空闲线程,如果没有,则创建新线程并放入池中。
    - 用于执行一些生存期很短的异步型任务。不适用于IO等长延时操作,因为这可能会创建大量线程,导致系统崩溃。
    - 使用SynchronousQueue作为阻塞队列,如果有新任务进入队列,必须队列中数据被其他线程处理,否则会等待。

    2.FixedThreadPool

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

    import java.util.concurrent.TimeUnit;
    
    public class ThreadRunner implements Runnable{
        private int num;
        private int timeout;
        public ThreadRunner(int num,int timeout){
            this.num = num;
            this.timeout = timeout;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
            try {
                TimeUnit.SECONDS.sleep(timeout);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class FixedThreadPoolMain {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);//有一个固定大小的线程池
    
            for(int i = 1;i<21;i++){
                pool.submit(new ThreadRunner(i,2));
            }
    
            pool.shutdown();
        }
    }

    总结:
    - 池中线程数量固定,不会发生变化
    - 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。
    - 适用一些很稳定很固定的正规并发线程,多用于服务器

    3.ScheduledExcutorPool

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

    ScheduledThreadPool中常用的ScheduleAtFixedRateScheduleWithFixedDelay

    * ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
    *                     即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
    * ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
    *                     即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
    *
    * ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
    * ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    
    public class ThreadRunner implements Runnable{
        private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");
    
        private int num;
        private int timeout;
        public ThreadRunner(int num,int timeout){
            this.num = num;
            this.timeout = timeout;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
            try {
                TimeUnit.SECONDS.sleep(timeout);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class ScheduledExcutorPoolMain {
        public static void main(String[] args) {
            ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);//线程池
    
            // 从现在开始5秒钟之后,每隔10秒钟执行一次ThreadRunner
            pool.scheduleAtFixedRate(new ThreadRunner(2,3), 5,10, TimeUnit.SECONDS);
    
            // 从现在开始5秒钟之后,每隔10秒钟执行一次job2
            pool.scheduleWithFixedDelay(new ThreadRunner(3,3), 5, 10, TimeUnit.SECONDS);
    
            /**
             * ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
             *                     即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
             * ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
             *                     即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
             *
             * ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
             * ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
             */
        }
    }

    总结:
    - 线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。
    - 只有当调度任务来的时候,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是出于轮询任务的状态

    4.SingleThreadExecutor

    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照提交顺序被执行

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    
    public class ThreadRunner implements Runnable{
        private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");
    
        private int num;
        private int timeout;
        public ThreadRunner(int num,int timeout){
            this.num = num;
            this.timeout = timeout;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
            try {
                TimeUnit.SECONDS.sleep(timeout);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class SingleThreadPool {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newSingleThreadExecutor();
            for(int i=1;i<21;i++){
                pool.submit(new ThreadRunner(i,5));
            }
            pool.shutdown();
        }
    }

    结果:

    pool-1-thread-1:当前时间:15:53:35.883,运行中,1
    pool-1-thread-1:当前时间:15:53:40.884,运行中,2
    pool-1-thread-1:当前时间:15:53:45.884,运行中,3
    pool-1-thread-1:当前时间:15:53:50.884,运行中,4
    pool-1-thread-1:当前时间:15:53:55.884,运行中,5
    pool-1-thread-1:当前时间:15:54:00.885,运行中,6
    pool-1-thread-1:当前时间:15:54:05.885,运行中,7
    pool-1-thread-1:当前时间:15:54:10.886,运行中,8
    pool-1-thread-1:当前时间:15:54:15.886,运行中,9
    pool-1-thread-1:当前时间:15:54:20.887,运行中,10
    pool-1-thread-1:当前时间:15:54:25.887,运行中,11
    pool-1-thread-1:当前时间:15:54:30.887,运行中,12
    pool-1-thread-1:当前时间:15:54:35.888,运行中,13
    pool-1-thread-1:当前时间:15:54:40.888,运行中,14
    pool-1-thread-1:当前时间:15:54:45.888,运行中,15
    pool-1-thread-1:当前时间:15:54:50.888,运行中,16
    pool-1-thread-1:当前时间:15:54:55.889,运行中,17
    pool-1-thread-1:当前时间:15:55:00.889,运行中,18
    pool-1-thread-1:当前时间:15:55:05.889,运行中,19
    pool-1-thread-1:当前时间:15:55:10.890,运行中,20

    总结:
    - 线程中只有一个线程在执行
    - 适用于有明确执行顺序但是不影响主线程的任务,压入池中的任务会按照队列顺序执行。
    - 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。

    源码地址:https://github.com/qjm201000/concurrent_executorService.git

  • 相关阅读:
    一个标准的类通常要拥有下面四个组成部分
    局部变量和成员变量的区别
    Java学习: 面向对象的使用与注意事项
    学习:内存的申请与释放
    虚拟内存与物理内存
    实现:win32实现EDIT控件读取和保存
    学习:生产者和消费者模式实现线程同步
    学习:线程互斥
    学习:多线程
    实现:服务程序增删
  • 原文地址:https://www.cnblogs.com/qjm201000/p/10156262.html
Copyright © 2011-2022 走看看