一 、@Async
1、启动类加上@EnableAsync
2、多线程任务
CompletableFuture<String> 返回值类型
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
/**
* @author LINK
*/
@Service
public class Asy1 {
@Async("asyncTaskExecutor")
public CompletableFuture<String> asy() throws InterruptedException {
for (int i = 0; i < 2; i++) {
System.out.println("异步线程开始-》"+ Thread.currentThread().getName() + i);
Thread.sleep(300);
}
return CompletableFuture.completedFuture("异步执行完啦");
}
}
2、线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 自定义线程池
*/
@Configuration
public class AsyncConfig {
@Bean()
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(20);
//队列容量
executor.setQueueCapacity(5000);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("自定义线程池1--》");
executor.initialize();
return executor;
}
@Bean()
public AsyncTaskExecutor asyncTaskExecutor2() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(20);
//队列容量
executor.setQueueCapacity(5000);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("自定义线程池1--》");
executor.initialize();
return executor;
}
}
3、TestController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
/**
* @author LINK
*/
@RestController
@RequestMapping("asy")
public class test1 {
@Autowired
private Asy1 asy1;
@RequestMapping("/show")
public String show() throws InterruptedException {
System.out.println("主线程开始-》"+ Thread.currentThread().getName() );
CompletableFuture<String> res = asy1.asy();
System.out.println("主线程结束-》"+ Thread.currentThread().getName() );
res.thenAccept(str->{
System.out.println(str);
});
return "主线程执行完毕,多线程还在继续";
}
}