1.编写配置类
package com.cc.myall.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class SpringAsync {
@Bean
public TaskExecutor taskExecutor(){
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(5);
//设置最大线程数
executor.setMaxPoolSize(10);
//设置队列容量
executor.setQueueCapacity(20);
//设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
//设置线程名称
executor.setThreadNamePrefix("Thred-");
//设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//等待所有线程任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
2.创建demo
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
@Component
@Slf4j
public class Hello {
@Async
public Future<Boolean> sayHello(String name) throws InterruptedException {
log.info(name+":Hello world!");
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
log.info("{}=={}",i,name);
}
return new AsyncResult<>(true);
}
}
3.编写配置类
@Autowired
Hello hello;
@Test
public void hello() throws Exception {
final ArrayList<Future<Boolean>> list = new ArrayList<>();
for (int i = 0; i < 11; i++) {
//阻塞调用返回值
final Future<Boolean> hel = hello.sayHello(String.valueOf(Math.random()));
list.add(hel);
if (list.size() == 5) {
while (true) {
for (int j = list.size() - 1; j >= 0; j--) {
final Future<Boolean> aBoolean = list.get(j);
if (aBoolean.isDone()) {
list.remove(j);
}
}
if (list.size() < 5) {
break;
}
}
}
}
while (true) {
for (int j = list.size() - 1; j >= 0; j--) {
final Future<Boolean> aBoolean = list.get(j);
if (aBoolean.isDone()) {
list.remove(j);
}
}
if (list.size() == 0) {
log.info("程序執行結束");
break;
}
}
}
4.效果展示
如果对你有帮助,多多评论转发与收藏!