• spring boot / cloud (四) 自定义线程池以及异步处理@Async obejct


    spring boot / cloud (四) 自定义线程池以及异步处理@Async

    前言

    什么是线程池?

    线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件),则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

    什么是异步处理?

    一个可以无需等待被调用函数的返回值就让操作继续进行的方法

    思路

    • 使用@Async来标记异步方法

    实现

    1.创建ThreadPoolConfig类,注意,需标记@EnableAsync

    @Configuration
    @EnableAsync
    public class ThreadPoolConfig {
    
      //其他
    
    }
    

    2.定义defaultThreadPool

      @Bean
      public Executor defaultThreadPool() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(线程大小);
        executor.setThreadPriority(优先级);
        executor.setThreadNamePrefix(名称前缀);
        executor.initialize();
        return executor;
      }
    

    3.编写异步测试方法,注意,需标记@Async

      @Async
      public Future<String> async() throws InterruptedException {
        final long time = 5000;
        Thread.sleep(time);
        return new AsyncResult<>("job done");
      }
    

    4.调用异步方法(如无需获取返回值的话,可直接调用),这里的样例是等待异步方法执行,然后获得返回值的场景

      public String asyncWait() throws InterruptedException, ExecutionException {
        Future<String> msg = demoService.async();
        final long time = 10000;
        while (true) {
          if (msg.isDone()) {
            break;
          }
          Thread.sleep(time);
        }
        return msg.get();
      }
    

    代码仓库 (博客配套代码)

    结束

    异步调用,提供了一种非阻塞形式的方法调用,在无需立即得到返回值的场景下,有助于提高系统的并发能力.


    想获得最快更新,请关注公众号

    想获得最快更新,请关注公众号

  • 相关阅读:
    专业词汇-数学-运算:四则运算
    专业词汇-数学-运算:逆运算
    专业词汇-数学:运算
    DNF Package Management-CentOS 8
    Change the HostName of CentOS 8
    CentOS8 修改SSH端口,禁用root登录,修改SSH协议
    CentOS8 Disable IPV6 and Selinux
    Ubuntu 20.04 Install SSH, Change SSH Port, Enable root
    ubuntu 20.04 重启网卡服务
    Ubuntu 20.04 Install Guest Additions for VirtualBox
  • 原文地址:https://www.cnblogs.com/itkk/p/7444098.html
Copyright © 2020-2023  润新知