# springasync **Repository Path**: mingliu123/springasync ## Basic Information - **Project Name**: springasync - **Description**: @Async应用 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-08-15 - **Last Updated**: 2024-08-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ​ 源码: 它是spring scheduling下的一个注解  在Java中,@Async注解是Spring框架提供的,用于支持异步方法调用。它允许你将一个方法标记为异步执行,这意味着该方法的调用不会阻塞当前线程,而是由Spring管理的异步任务执行器在后台线程池中执行。 下面是如何在Spring中使用@Async的基本步骤: @Configuration @EnableAsync public class AsyncConfig { @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(20); executor.initialize(); return executor; } } SimpleAsyncTaskExecutor  而它不是一个线程池的实现类,它只是不断的创建线程然后执行任务,会导致无限的创建线程,后果很严重 protected void doExecute(Runnable task) { Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task)); thread.start(); } @Component public class MyService { @Async public void doSomethingAsync() { // 异步执行的代码 } } @Autowired private MyService myService; public void someMethod() { CompletableFuture future = myService.doSomethingAsync(); // 这里可以继续执行其他操作,不会被doSomethingAsync阻塞 } 请记住,在使用@Async时,确保你的Spring Bean是在Spring容器管理之下的,并且要正确处理异步方法的异常和返回结果。如果方法抛出异常,而你没有处理,那么这些异常可能会丢失或者导致不可预期的行为。 ​> > http://t.csdnimg.cn/wyblc