springboot+多线程简单实现

36次阅读

共计 969 个字符,预计需要花费 3 分钟才能阅读完成。

搭建 springboot 环境创建 ThreadConfig
/**
* 线程
*
* @author zhoumin
* @create 2018-09-18 13:58
*/
@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(500);
executor.setKeepAliveSeconds(30000);
executor.initialize();
return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
创建 service 和接口
void test(int i);
service 实现类
@Override
@Async
public void test(int i) {
System.out.println(“ 线程 ” + Thread.currentThread().getName() + ” 执行异步任务:” + i);
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest {

}

/**
* @author zhoumin
* @create 2018-09-18 14:12
*/
public class ThreadTest extends BaseTest{
@Autowired
private DeviceStatisticsTaskService deviceStatisticsTaskService;

@org.junit.Test
public void threadTest() {
for (int i = 0; i < 5000; i++) {

deviceStatisticsTaskService.test(i);
}
}
}

正文完
 0