配置类
@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个
文章来源地址https://www.toymoban.com/news/detail-706954.html
文章来源:https://www.toymoban.com/news/detail-706954.html
到了这里,关于构造函数注入指定bean名称的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!