@Service
//@EnableAsync
public class TestAsyncService {
// ???@Async
public void serviceTest() {
// 这里执行实际的业务逻辑,在这里我们就是用一个简单的遍历来模拟
Arrays.stream(new int[]{1,2,3,4,5,6,7,8,9,10}).forEach(t -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("获取主线程名称:" + Thread.currentThread().getName());
System.out.println("获取number为:" + t) ;
});
}
}
@RestController
public class ThreadController1 {
@Autowired
private TestAsyncService service;
/**
* 使用传统方式测试
*/
@GetMapping("/t1")
public void test() {
System.out.println("获取主线程名称:" + Thread.currentThread().getName());
service.serviceTest();
System.out.println("执行成功,返回结果");
}
}
@RestController
public class ThreadController2 {
@Autowired
private TestAsyncService asyncService;
/**
* 使用传统方式测试
*/
@GetMapping("/t2")
public void test() {
System.out.println("获取主线程名称:" + Thread.currentThread().getName());
/**
* 定义一个线程池
* 核心线程数(corePoolSize):1
* 最大线程数(maximumPoolSize): 1
* 保持连接时间(keepAliveTime):50000
* 时间单位 (TimeUnit):TimeUnit.MILLISECONDS(毫秒)
* 阻塞队列 new LinkedBlockingQueue<Runnable>()
*/
ThreadPoolExecutor executor = new ThreadPoolExecutor(1,5,50000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
// 执行业务逻辑方法serviceTest()
executor.execute(new Runnable() {
@Override
public void run() {
asyncService.serviceTest();
}
});
System.out.println("执行完成,向用户响应成功信息");
}
}
@RestController
public class ThreadController3 {
@Autowired
private TestAsyncService asyncService;
/**
* 使用@Async来实现
*/
@GetMapping("/t3")
public void test() {
System.out.println("获取主线程名称:" + Thread.currentThread().getName());
// 异步调用
asyncService.serviceTest();
System.out.println("执行完成,向用户响应成功信息");
}
}