首页 > 其他分享 >后台用异步线程调用的场景与常用方式

后台用异步线程调用的场景与常用方式

时间:2023-06-18 11:45:16浏览次数:48  
标签:异步 int private 线程 executor 后台 public

一.异步执行的场景:

完成业务后,发短信、发邮件、微信公众号等消息推送提示的功能,可以采用异步执行。

在导入数量量过大等情况下,可以使用异步导入的方式,提高导入时间等。

...等等

二.实现的方式:

1.springboot中,进行线程池配置,然后用@Async标识异步执行方法即可,如下:(需要注意的@EnableAsync和@Async不能在同一个类中 | 实现AsyncConfigurer的类只能有一个 | 这种方式的异步没有返回值,不适用与需要等待执行完成的场景。)

@Configuration
@EnableAsync
public class ExecutorConfig implements AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.keep_alive_seconds}")
    private int keepAliveSeconds;
    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    @Bean(name = "asyncExecutor")
    public Executor asyncServiceExecutor() {
        logger.info("开启SpringBoot的线程池!");

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(maxPoolSize);
        // 设置缓冲队列大小
        executor.setQueueCapacity(queueCapacity);
        // 设置线程的最大空闲时间,超过了核心线程数之外的线程,在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置线程名字的前缀,设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix(namePrefix);
        // 设置拒绝策略:当线程池达到最大线程数时,如何处理新任务
        // CALLER_RUNS:在添加到线程池失败时会由主线程自己来执行这个任务,
        // 当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务;如果执行程序已被关闭,则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 线程池初始化
        executor.initialize();

        return executor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncServiceExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> logger.error(String.format("执行异步任务'%s'", method), ex);
    }
}
public class useAsync {

       @Async(name = "asyncExecutor")
   public void asyncMethod(){
     // 异步执行的业务代码 
  }
 }

 2.需要返回值的异步线程池调用线程方式:

    public void sum() throws ExecutionException, InterruptedException {
            ExecutorService executorService = Executors.newFixedThreadPool(4);
            List<Future<Integer>> futureList = new ArrayList<>();
            for (int i=0;i<600;i++){
                Future<Integer> futureSum = executorService.submit(new SumCall(Integer.valueOf(i)));
                futureList.add(futureSum);
            }
            // 关闭线程池
            executorService .shutdown();
            // 获取所有并发任务的运行结果,若需要等待并发任务执行完成的结果,在做其他业务,这里使用while循环配合一个完成标识flag就可以了。
            for (Future<Integer> future : futureList){
                System.out.println(future.get());
            }
    }
    
    class SumCall implements Callable<Integer> {
        private int plus;

        public SumCall(int plus) {
            this.plus= plus;
        }

        @Override
        public Integer call() throws Exception {
            return 1+plus;
        }
    }

参考链接: https://blog.csdn.net/lemon_TT/article/details/122905103

参考链接:https://blog.csdn.net/ClaireCheney/article/details/107109340

 

标签:异步,int,private,线程,executor,后台,public
From: https://www.cnblogs.com/duiyuedangge/p/17488897.html

相关文章

  • Java中线程等待和唤醒
    Java中线程等待和唤醒本文主要是对Java中线程等待、唤醒相关的内容进行总结。线程的生命周期和状态Java线程在运行的生命周期中的指定时刻只可能处于下面6种不同状态的其中一个状态:NEW:初始状态,线程被创建出来但没有被调用start()。RUNNABLE:运行状态,线程被调用了s......
  • IU5365具有NTC及电池过放电电压保护功能,3A异步降压型铅酸电池充电管理IC
    IU5365E是一款异步降压型铅酸电池充电管理IC。集成功率MOS,具有最大3A的充电电流能力,充电电流可以通过外部电阻灵活可调。IU5365E通过设置合适的外围电阻,具有对电池的NTC保护功能。IU5365E通过外部电阻,可独立调节过充电压。IU5365E具有完善的保护功能,包括输入欠压和过压保护、电池充......
  • Spring框架中的线程池
    Spring框架中的线程池使用Java的ExecutorService接口实现ExecutorService是Java提供的用于管理线程池的高级工具。下面是在Spring框架中使用线程池的一般步骤:导入所需的依赖首先,确保你的项目中包含了使用线程池所需的依赖。通常情况下,你可以使用SpringBoot来创建项目,它会自动包含......
  • Java线程池与异常处理
    线程池线程池的创建代码ThreadPoolExecutorthreadPoolExecutor=newThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,......
  • 如何让UnityEditor后台运行
    最近在玩ml-agents,发现训练的时候点击别的窗口,UnityEditor就挂起不接着运行了。google了一下发现可以通过点击Edit->ProjectSettings->Player->ResolutionandPresentation,然后勾选RunInBackground即可解决该问题:......
  • c++线程安全队列--有锁
    C++线程安全队列是一种数据结构,用于在多线程环境中安全地共享数据。它提供了一组功能,确保多个线程可以同时读取和写入队列,而不会导致竞争条件或数据损坏。C++线程安全队列的常见功能:入队操作(Enqueue):将一个元素添加到队列的尾部。这个操作必须是原子的,以确保在多线程环境中不会......
  • JAVA 线程安全案例
    #线程安全案例##使用原子类来实现资源的安全保护```javapublicclassAtomicSafeExample{staticCountDownLatchcountDownLatch=newCountDownLatch(2);publicstaticvoidmain(String[]args)throwsInterruptedException{Threadthread=newThrea......
  • 多线程
    多线程线程介绍每个进程都会有一个主线程,在创建进程时创建,往后创建的线程都属于子线程;线程在进程里不断抢占运行时间片;当进程遇到return结束,所有的线程全部结束。线程分类线程主要分为用户级线程和内核级线程用户级线程主要解决上下文切换问题,其调度由用户控制内核级线程......
  • c#中tcp异步
    usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;n......
  • 多线程
    1.进程和线程的定义进程:引用程序的执行实例(一个应用对应一个进程)线程:CPU调用和分派的基本单元,进程中执行运算的最小单位2.创建线程的种类继承java.lang.Thread类实现java.lang.Runnable接口3.继承java.lang.Thread类(1)定义MyThread类继承Thread类(2)重写run()方法,编写线程......