SpringBoot线程池+多线程

kyaa111 3年前 ⋅ 650 阅读

启动类上加注解


@SpringBootApplication
@EnableAsync
public class SpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringApplication.class, args);
    }

}

业务逻辑类


@Component
public class MultiThreadTest {
    @Async
    public Future<Boolean> test(int i) {
		
        //业务逻辑
		System.out.println(i);

        return new AsyncResult<>(true);
    }
}


@RestController
public class TestController {

    @Autowired
    private MultiThreadTest multiThreadTest;

    @GetMapping("/test")
    public String test() throws Exception {
    	List<Future<Boolean>> threadResult = getThreadResultList(10);
    	for(int i = 0; i < 10; i++){
        	Future<Boolean> booleanFuture = multiThreadTest.test(i);
            threadResult.add(booleanFuture);
        }
        //获取线程执行结果,get是阻塞的
        for (Future<Boolean> isSuccess : threadResult) {
            Boolean result = isSuccess.get();
            if (!result) {
                throw new Exception("errorMsg");
            }
        }
        return "SUCCESS";
    }
}

代码是从工程内扒下来的,可能会有地方编译错误