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字符串先输出,方法异步执行

Spring @Async demo

 

相关文章:

  • 2021-12-02
  • 2022-12-23
  • 2022-02-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-26
  • 2021-04-20
猜你喜欢
  • 2021-10-03
  • 2022-12-23
  • 2022-01-07
  • 2021-09-25
  • 2021-11-17
相关资源
相似解决方案