import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Future; @Configuration @EnableAsync public class SpringAsyncConfig { @Bean("taskExecutor") public TaskExecutor taskExecutor(){ ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setThreadNamePrefix("taskExecutor"); threadPoolTaskExecutor.setCorePoolSize(10); threadPoolTaskExecutor.setMaxPoolSize(30); threadPoolTaskExecutor.setQueueCapacity(100); threadPoolTaskExecutor.afterPropertiesSet(); return threadPoolTaskExecutor; } @Async //标注使用 public void asyncMethodWithVoidReturnType() { System.out.println("Execute method asynchronously. " + Thread.currentThread().getName()); } @Async public Future<String> asyncMethodWithReturnType() { System.out.println("Execute method asynchronously - " + Thread.currentThread().getName()); try { Thread.sleep(5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAsyncConfig.class); SpringAsyncConfig bean = (SpringAsyncConfig) context.getBean("springAsyncConfig"); bean.asyncMethodWithReturnType(); } }
标签:Spring,Boot,springframework,public,org,import,threadPoolTaskExecutor,annotation, From: https://www.cnblogs.com/fan119735966/p/17025355.html