zoukankan      html  css  js  c++  java
  • 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!
  • 相关阅读:
    结对-贪吃蛇游戏结对编项目设计文档
    java基础语法day04
    java基础语法day03
    轻量化ViewController的几个小技巧
    __weak与__block修饰符的区别
    OC与Swift的主要区别
    copy与retain /深拷贝与浅拷贝
    如何理解MVC设计模式
    iOS常见加密方法
    关于RunLoop
  • 原文地址:https://www.cnblogs.com/luckygxf/p/15417264.html
Copyright © 2011-2022 走看看