# Java异步调用方法的3种方式 **Repository Path**: fpfgitmy_admin/java-async-three-method ## Basic Information - **Project Name**: Java异步调用方法的3种方式 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-04-28 - **Last Updated**: 2021-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### Java异步调用方法 #### 使用多线程 + 多线程本身就是异步的方式 + 涉及技术:[多线程]() 1. 直接创建线程 + 代码示例 ``` @GetMapping("/async1") public void testAsync1() { // 直接创建线程 Thread thread = new Thread() { @Override public void run() { // 需要异步的方法 demoService.testAsync(); } }; thread.start(); // 执行主要业务方法 demoService.testMainMethod(); } ``` 2. 使用线程池创建线程 ``` @GetMapping("/async1") public void testAsync1() { // 使用线程池的方式 ExecutorService service = Executors.newCachedThreadPool(); service.execute(new Runnable() { @Override public void run() { // 需要异步的方法 demoService.testAsync(); } }); // 执行主要业务方法 demoService.testMainMethod(); } ``` #### 启动SpringBoot的异步模式 + 注意: + `@Async`注解需要写在Spring管理的类中 + 被该注解标注的方法,不能在当前类中调用 + 涉及技术:[@Async]()、[Spring的AOP]()、[@EnableAsync]() + 代码示例: 1. 在SpringBoot启动类上方添加`@EnableAsync` ``` @EnableAsync @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 2. 在调用方法上添加`@Async` ``` @Override @Async public void testAsync() { System.out.println("这是个测试异步的方法"); } ``` 3. 进行调用 ``` @GetMapping("/async1") public void testAsync1() { // 需要异步的方法 demoService.testAsync(); // 执行主要业务方法 demoService.testMainMethod(); } ``` #### 使用Future + 简介: + 代码示例: 1. 编写异步方法 ``` private Future longTimeMethod2() { //创建线程池 ExecutorService threadPool = Executors.newCachedThreadPool(); //获取异步Future对象 Future future = threadPool.submit(new Callable() { @Override public Integer call() throwsException { return longTimeMethod(); } }); return future; } ``` 2. 进行异步方法调用 ``` @GetMapping("/async1") public void testAsync1() { // 需要异步的方法 Future future = demoService.asyncAdd(); // 获取返回值 try { Integer reValue = (Integer) future.get(); System.out.println("获取到的返回值"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } // 执行主要业务方法 demoService.testMainMethod(); } ```