• Spring @Async demo


    config配置类AsyncConfig.java

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.AsyncConfigurer;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.Executor;
    
    
    @Configuration
    @ComponentScan("com.gxf.service")
    @EnableAsync
    public class AsyncConfig implements AsyncConfigurer {
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(100);
            executor.setQueueCapacity(10);
            executor.initialize();
            return executor;
        }
    }
    AsyncServiceImpl.java

    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class AsyncServiceImpl {
        @Async
        public void asyncMethod()  {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("async method");
        }
    }

    Main方法

    public class Main {
        public static void main(String[] args) throws InterruptedException {
            AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AsyncConfig.class);
            AsyncServiceImpl asyncService = ac.getBean(AsyncServiceImpl.class);
            asyncService.asyncMethod();
            System.out.println("Main");
            Thread.sleep(1000000);
        }
    }

    Main字符串先输出,方法异步执行

    Please call me JiangYouDang!
  • 相关阅读:
    S3C44b0x通用延时函数,延时time个100us函数理解
    LeetCode-058-最后一个单词的长度
    LeetCode-053-最大子序和
    LeetCode-035-搜索插入位置
    LeetCode-027-移除元素
    LeetCode-026-删除有序数组中的重复项
    LeetCode-025-K 个一组翻转链表
    LeetCode-024-两两交换链表中的节点
    LeetCode-023-合并K个升序链表
    LeetCode-021-合并两个有序链表
  • 原文地址:https://www.cnblogs.com/luckygxf/p/15417264.html
Copyright © 2020-2023  润新知