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);
        }
    }
}

你可能感兴趣的:(maven,intellij-idea,mysql,apache,spring)