• Java多线程/spring boot多线程


    总结

    1. Main方法上开启异步:@EnableAsync
    2. (可选)配置线程池:配置ThreadPoolTaskExecutor,不配置则默认使用SimpleAsyncTaskExecutor
    3. 异步方法:@Async(“线程池名”)异步注解,放到方法上,表示调用该方法的线程与执行此方法的线程异步(调用线程与执行线程异步)

    注意

    ThreadPoolTaskExecutor中的线程都是守护线程,用户线程执行完毕,杀死所有守护线程
    ThreadPoolTaskExecutor对象调用shutdown()方法时是否等待任务执行完毕再尝试shutdown()

    // true-等待正在执行任务的线程执行完毕再尝试shutdown(),false-不等待,直接shutdown(),以抛出java.lang.InterruptedException异常的方式shutdown
    // true-类似java线程池的shutdown(), false-类似java线程池的shutdownNow()
    threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    
    • 1
    • 2
    • 3

    @Async使用注意

    • @Async失效:static修饰异步方法(spring boot不能扫描到这个方法)
    • @Async失效:一个类中的方法相互调用不会触发异步
    • @Transactional失效:@Async方法上使用@Transactional

    使用

    pom.xml

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
    
        <groupId>com.xcrjgroupId>
        <artifactId>springbootbasicartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starterartifactId>
                <version>2.7.1version>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <version>2.7.1version>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>RELEASEversion>
                <scope>testscope>
            dependency>
        dependencies>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    main @EnableAsync

    package com.xcrj;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableAsync;
    
    // 开启异步
    @EnableAsync
    @SpringBootApplication
    public class ApplicationMain {
        public static void main(String[] args) {
            SpringApplication.run(ApplicationMain.class, args);
            System.out.println("启动");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    configuration ThreadPoolTaskExecutor

    package com.xcrj.configuration;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.ThreadPoolExecutor;
    
    @Configuration
    public class AsyncMeConfiguration {
    
        // 配置线程池ThreadPoolTaskExecutor threadPoolTaskExecutor01
        @Bean("threadPoolTaskExecutor01")
        public ThreadPoolTaskExecutor getAsyncExecutor() {
            /**
             *  corePoolSize:核心线程数,线程池维持的线程数
             *  maximumPoolSize:池中最多线程数
             *  keepAliveTime:大于核心线程数的线程存活时间
             *  unit:存活时间单位
             *  workQueue:任务队列 (BlockingQueue)(queueCapacity > 0 ? new LinkedBlockingQueue(queueCapacity) : new SynchronousQueue());
             *  threadFactory:线程工厂
             *  RejectedExecutionHandler:任务拒绝策略处理器
             *  waitForTasksToCompleteOnShutdown:是否等待正在执行任务的线程执行完毕再尝试shutdown()
             */
            ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
            threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
            threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
            threadPoolTaskExecutor.setQueueCapacity(200);
            threadPoolTaskExecutor.setKeepAliveSeconds(10);
            threadPoolTaskExecutor.setThreadNamePrefix("asyncMe");
            threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            // true-等待正在执行任务的线程执行完毕再尝试shutdown(),false-不等待,直接shutdown(),以抛出java.lang.InterruptedException异常的方式shutdown
            // true-类似java线程池的shutdown(), false-类似java线程池的shutdownNow()
            threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
            threadPoolTaskExecutor.initialize();
            return threadPoolTaskExecutor;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    service方法 @Async

    package com.xcrj.service;
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    @Service
    public class AsyncMeService {
        // 使用threadPoolTaskExecutor01线程池中的线程异步执行service1
        @Async("threadPoolTaskExecutor01")
        public void service1() throws InterruptedException {
            System.out.println("开始服务1");
            // 执行任务耗时
            Thread.sleep(5000);
            System.out.println("结束服务1");
        }
    
        // 使用threadPoolTaskExecutor01线程池中的线程异步执行service2
        @Async("threadPoolTaskExecutor01")
        public void service2() throws InterruptedException {
            System.out.println("开始服务2");
            // 执行任务耗时
            Thread.sleep(2000);
            System.out.println("结束服务2");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    test

    package com.xcrj.service;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import javax.annotation.Resource;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class TestAsyncMeService {
        @Resource
        private AsyncMeService asyncMeService;
        @Resource(name = "threadPoolTaskExecutor01")
        private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    
    
        @Test
        public void testAsync() throws InterruptedException {
            asyncMeService.service1();
            asyncMeService.service2();
    
            threadPoolTaskExecutor.shutdown();
            // ThreadPoolTaskExecutor中的线程都是守护线程,用户线程执行完毕,杀死所有守护线程
            Thread.sleep(10000);
            System.out.println("结束test线程");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
  • 相关阅读:
    Hadoop的UI页面介绍
    golang语言开发:1.在windows下使用vscode搭建golang环境并进行调试
    联想M7216NWA打印一体机墨粉清零方法
    PopupWindow第一次弹出的位置和第二次不一致
    凌特杯,第二届,数字音频传输。simulink matlab
    Mybatis-Plus从入门到入土
    格式化数据写入sprintf的用法
    2023-11-17 服务器开发-性能分析-intel-vtune-安装
    c++ —— 模板的进阶使用
    FaceBook 遭遇有史以来全球最大宕机
  • 原文地址:https://blog.csdn.net/baidu_35805755/article/details/125897358