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!
原文地址:https://www.cnblogs.com/luckygxf/p/15417264.html