多线程——线程池1

内容分享5小时前发布
0 0 0

1. 线程池概念和作用

线程池:其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。

线程池作用就是限制系统中执行线程的数量

为什么要用线程池:
1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。

2. 线程池的继承关系



 顶级线程池接口        Executor
 1.void execute(Runnable command);         执行任务
                        |
 线程池接口         ExecutorService
 1.void shutdown();                        关闭线程池
 2.<T> Future<T> submit(Callable<T> task); 执行任务
 3. Future<?> submit(Runnable task);       执行任务
                        |
 定时任务线程池  ScheduledExecutorService
 自定义线程池    ThreadPoolExecutor

3. Executors 线程池的工具类

1.public static ExecutorService newSingleThreadExecutor()
  newSingleThreadExecutor
  创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。



        //单线程的线程池
        ExecutorService pool = Executors.newSingleThreadExecutor();
 
        //执行任务
        pool.execute(new MyRunnable()); 
        pool.execute(new MyRunnable());
        pool.execute(new MyRunnable());  
        pool.execute(new MyRunnable());  
 
        //关闭线程池
        pool.shutdown();

多线程——线程池1
2.public static ExecutorService newFixedThreadPool(int nThreads)
  newFixedThreadPool
  创建固定大小的线程池。
  每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。
  线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。



        ExecutorService pool = Executors.newFixedThreadPool(3);
 
        //执行任务
        pool.execute(new MyRunnable());  
        pool.execute(new MyRunnable());   
        pool.execute(new MyRunnable());   
        pool.execute(new MyRunnable());   
        pool.execute(new MyRunnable());  
 
        pool.shutdown();

多线程——线程池1
3.public static ExecutorService newCachedThreadPool()
  newCachedThreadPool
  创建一个可缓存的线程池。
  如果线程池的大小超过了处理任务所需要的线程,那么会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。



        ExecutorService pool = Executors.newCachedThreadPool();
 
        //执行任务
        pool.execute(new MyRunnable());   
        pool.execute(new MyRunnable());  
        pool.execute(new MyRunnable()); 
        pool.execute(new MyRunnable());  
        pool.execute(new MyRunnable()); 
 
        pool.shutdown();

多线程——线程池1
4.public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  newScheduledThreadPool
  创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

  场景:SpringTask 定时任务,它的底层原理是newScheduledThreadPool线程池。



        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
 
        /**
         * 定时执行的任务  scheduleAtFixedRate()
         * 第一个参数:执行的任务 Runnable 对象
         * 第二个参数:延时时间
         * 第三个参数:周期频率
         * 第四个参数:时间单位
         */
        pool.scheduleAtFixedRate(
                ()-> System.out.println(LocalDateTime.now()),
                1,
                1,
                TimeUnit.SECONDS
        );

多线程——线程池1

4. 接口

— Executor        线程池顶级接口 ,不是一个线程池,而只是一个执行线程的工具
— ExecutorService 线程池接口
— ScheduledExecutorService  定时执行任务的线程池接口
— ThreadPoolExecutor        自定义线程池的类

ExecutorService 线程池接口
1.Future<?> submit(Runnable task);  传入Runnable任务对象,无法通过Future中的get()获取返回值,为null
2.<T> Future<T> submit(Callable<T> task);  传入Callable任务对象,可以通过Future中的get()获取返回值



        //以submit(Runnable对象)为例
        Future<?> future1 = pool.submit(new MyRunnable());
        Object result1 = null;
        try {
            result1 = future1.get();   
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("result1 = "+result1);
 
        Future<?> future2 = pool.submit(new MyRunnable());
        Object result2 = null;
        try {
            result2 = future2.get();   
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("result2 = "+result2);

多线程——线程池1



        //以submit(Callable对象)为例
        Future<?> future1 = pool.submit(new MyCallable());
        Object result1 = null;
        try {
            result1 = future1.get();  
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("result1 = "+result1);
 
        Future<?> future2 = pool.submit(new MyCallable());
        Object result2 = null;
        try {
            result2 = future2.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("result2 = "+result2);

多线程——线程池1

submit() 和 execute() 区别:
1.Executor线程池顶级接口中,提供的void execute(Runnable command);方法
  ExecutorService 线程池接口,提供给 Future<?> submit(Runnable task);  传入Runnable任务对象
  ExecutorService 线程池接口,提供给 <T> Future<T> submit(Callable<T> task);  传入Callable任务对象
2.submit()执行任务时,可以带回Future,通过Future的get()获取线程执行任务后的结果,建议必须搭配Callable一起使用
3.submit()对于出现异常后的处理更加完善,因为实现Callable接口,重写call()会抛出异常,可以通过Future中的get()获取返回值,需要处理ExecutionException,抛出异常时可以阻止其它的任务执行

© 版权声明

相关文章

暂无评论

none
暂无评论...