配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@EnableAsync
@Configuration
public class ExecutorConfig {
private int corePoolSize = 6;
private int maxPoolSize = 6;
private int keepAliveSeconds = 60;
private int queueCapacity = 1;
private boolean allowCoreThreadTimeOut = false;
@Bean("asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
Service
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.ui.context.Theme;
import java.util.Random;
import java.util.concurrent.Future;
@Service
@Slf4j
public class AsyncService {
@Async("asyncExecutor")
public Future<String> executeAsync(int a) {
String msg = "500";
try {
Thread.sleep(a * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":我已经输出了");
return new AsyncResult<String>(msg);
}
}
Controller
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
@Slf4j
@RestController
public class ThreadTest {
@Autowired
private AsyncService asyncService;
@GetMapping("threadTest")
public String OJ() {
Future<String> s1 = asyncService.executeAsync(1);
Future<String> s2 = asyncService.executeAsync(2);
Future<String> s3 = asyncService.executeAsync(3);
Future<String> s4 = asyncService.executeAsync(4);
Future<String> s5 = asyncService.executeAsync(5);
Future<String> s6 = asyncService.executeAsync(6);
Future<String> s7 = asyncService.executeAsync(7);
while (!(s1.isDone() && s2.isDone() && s3.isDone() && s4.isDone())) {
try {
Thread.sleep(1000);
System.out.println("还没运行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("运行结束");
return "ssss";
}
}