springboot+多线程简单实现

搭建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);
        }
    }
}
    原文作者:盘子
    原文地址: https://segmentfault.com/a/1190000017924478
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞