配置类
@Configuration
public class ThreadPoolTaskExecutorConfig {
@Bean
public ThreadPoolTaskScheduler syncScheduler() {
ThreadPoolTaskScheduler syncScheduler = new ThreadPoolTaskScheduler();
syncScheduler.setPoolSize(10);
syncScheduler.setThreadGroupName("syncTg");
syncScheduler.setThreadNamePrefix("syncThread-");
syncScheduler.initialize();
return syncScheduler;
}
@Bean(name ="syncScheduler2")
public ThreadPoolTaskScheduler syncScheduler2() {
ThreadPoolTaskScheduler syncScheduler = new ThreadPoolTaskScheduler();
syncScheduler.setPoolSize(100);
syncScheduler.setThreadGroupName("syncTg");
syncScheduler.setThreadNamePrefix("syncThread-");
syncScheduler.initialize();
return syncScheduler;
}
}
测试类
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
//@RunWith(SpringRunner.class)
@SpringBootTest
public class DynamicTaskServiceTest {
private final ThreadPoolTaskScheduler syncScheduler;
@Autowired
public DynamicTaskServiceTest(@Qualifier("syncScheduler2") ThreadPoolTaskScheduler syncScheduler) {
this.syncScheduler = syncScheduler;
}
@Test
public void test() {
for (int i = 0; i < 500; i++) {
syncScheduler.schedule(testRunnable(), getNowDate());
}
try {
// 主线程延迟,不然会导致子线程被打断
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
public Runnable testRunnable() {
return () -> {
System.out.println(Thread.currentThread().getName() + "线程开始");
try {
// 每次循环都要等待10毫秒,模拟阻塞
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + "线程结束");
};
}
}
如图执行结果,通过@Qualifier指定调用syncScheduler2线程池100个