异步调用相对的是同步调用。java
同步方法调用的时候必须是按照顺序执行的,上一行代码执行完,才会执行下一行。而异步方法调用是至关于多个线程执行,不须要等待上一行代码的执行结果。web
首先测试方法同步的状况:spring
controller:springboot
package springboot_async.async_test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private MyService myService; @RequestMapping("/test") public String getInedx() throws InterruptedException { System.out.println("开始访问"); long l1 = System.currentTimeMillis(); myService.JobOne(); myService.JobTwo(); myService.JobThree(); long l2 = System.currentTimeMillis(); System.out.println("结束访问,用时"+(l2-l1)); return "finished"; } }
service:app
package springboot_async.async_test; import org.springframework.stereotype.Service; @Service public class MyService { public void JobOne() throws InterruptedException { System.out.println("开始执行任务一"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务一用时"+(l2-l1)); } public void JobTwo() throws InterruptedException { System.out.println("开始执行任务二"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务二用时"+(l2-l1)); } public void JobThree() throws InterruptedException { System.out.println("开始执行任务三"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务三用时"+(l2-l1)); } }
启动类:异步
package springboot_async; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
运行结果,咱们以运行四次为例:async
咱们能够看到屡次实验运行的结果都是按照调用方法的顺序进行执行。测试
下面咱们使用springboot提供的@Async来实现异步方法调用。线程
首先要在启动类上面使用@EnableAsync开始异步方法调用,而后在你要调用的每个方法上面都要添加@Async,代表异步调用该方法。至关于开启了新的线程,在调用该方法的时候不须要等待上一行代码是否执行完成。3d
conrtoller不须要作修改。
service:
package springboot_async.async_test; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class MyService { @Async public void JobOne() throws InterruptedException { System.out.println("开始执行任务一"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务一用时"+(l2-l1)); } @Async public void JobTwo() throws InterruptedException { System.out.println("开始执行任务二"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务二用时"+(l2-l1)); } @Async public void JobThree() throws InterruptedException { System.out.println("开始执行任务三"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务三用时"+(l2-l1)); } }
启动类:
package springboot_async; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
运行测试一:
运行测试二:
运行测试三:
通过测试能够看到任务执行的顺序是随机的,与方法调用的顺序无关,就说明这些方法是异步调用的。
在上面的测试中咱们也能够发现主调用方法controller没有等到调用方法执行完就结束了当前的任务,那么咱们若是想要知道在整个任务调用的三个方法所有执行完总共的时长该怎么办呢,下面就能够用到异步回调。
异步回调就是让每一个被调用的方法返回一个Future类型的值,而Spring提供了一个Future接口的子类:AsyncResult,因此咱们能够返回的时候new一个AsyncResult类型的值。
Future接口及实现类:
Futrue的方法:
isDone()返回Boolean类型值,用来判断该异步任务是否执行完成,若是执行完成,则返回true,若是未执行完成,则返回false.
cancel(boolean mayInterruptRunning)返回boolean类型值,参数也是一个boolean类型的值,用来传入是否能够打断当前正在执行的任务。若是参数是true且当前任务没有执行完成 ,说明能够打断当前任务,那么就会返回true,若是当前任务尚未执行,那么无论参数是true仍是false,返回值都是true,若是当前任务已经完成,那么无论参数是true仍是false,那么返回值都是false,若是当前任务没有完成且参数是false,那么返回值也是false。总结下来就是:1.若是任务还没执行,那么若是想取消任务,就必定返回true,与参数无关。2.若是任务已经执行完成,那么任务必定是不能取消的,因此此时返回值都是false,与参数无关。3.若是任务正在执行中,那么此时是否取消任务就看参数是否容许打断(true/false)。
isCancelled()返回的是boolean类型,若是是上面总结的第三种状况,这才是真正意义上有机会被取消的任务,那么此时若是上面的方法返回的是true,那么说明任务取消成功了,则这个方法返回的也就是true。
get()返回的是在异步方法中最后return 的那个对象中的value的值。
get(long timeout,TimeUnit unit)这个方法和get()的功能是同样的(在方法执行没有超时的状况下效果是同样的),只不过这里参数中设置了超时时间,由于get()在执行的时候是须要等待回调结果的,是阻塞在那里的,若是不设置超时时间,它就阻塞在那里直到有了任务执行完成。咱们设置超时时间,就能够在当前任务执行过久的状况下中断当前任务,释放线程,这样就不会致使一直占用资源。参数一是时间的数值,参数二是参数一的单位,能够在TimeUnit这个枚举中选择单位。若是任务执行超时,则抛出TimeOut异常,返回的message就是null。
TimeOut枚举的值:
使用异步回调:
在controller中无限循环判断异步方法是否执行完成。
在service的方法中返回Future值。
controller:
package springboot_async.async_test; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private MyService myService; @RequestMapping("/test") public String getInedx() throws InterruptedException, ExecutionException { System.out.println("开始访问"); long l1 = System.currentTimeMillis(); Future<String> r1 = myService.JobOne(); Future<String> r2 = myService.JobTwo(); Future<String> r3 = myService.JobThree(); while(true) {//死循环,每隔2000ms执行一次,判断一下这三个异步调用的方法是否全都执行完了。 if(r1.isDone() && r2.isDone() && r3.isDone()) {//使用Future的isDone()方法返回该方法是否执行完成 //若是异步方法所有执行完,跳出循环 break; } Thread.sleep(2000);//每隔2000毫秒判断一次 } long l2 = System.currentTimeMillis();//跳出while循环时说明此时三个异步调用的方法都执行完成了,此时获得当前时间 String result = r1.get(); System.out.println("结束访问,用时"+(l2-l1)); System.out.println("使用get方法得到的返回内容:"+result); return "finished"; } }
service :
package springboot_async.async_test; import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; @Service public class MyService { @Async public Future<String> JobOne() throws InterruptedException { System.out.println("开始执行任务一"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务一用时"+(l2-l1)); return new AsyncResult<String>("任务一完成");//可使用try,catch定义在正常完成时返回一个success信息,出现异常时返回error信息。 } @Async public Future<String> JobTwo() throws InterruptedException { System.out.println("开始执行任务二"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务二用时"+(l2-l1)); return new AsyncResult<String>("任务二完成"); } @Async public Future<String> JobThree() throws InterruptedException { System.out.println("开始执行任务三"); long l1 = System.currentTimeMillis(); Thread.sleep(2000); long l2 = System.currentTimeMillis(); System.out.println("任务三用时"+(l2-l1)); return new AsyncResult<String>("任务三完成"); } }
执行结果:
此时咱们就获得了全部异步任务所有执行完成的时间,所有执行完成后才让整个controller执行结束。并且咱们也发如今controller中调用Future的get()时,获得的就是JobOne()方法中return new AsyncResult中的值。
下面咱们看一下使用有参的get()方法的超时效果,这里以JobTwo来测试,特别要注意get(timeout,unit)放的位置是在while循环以前,也就是任务尚未执行完成以前:
controller:
@RestController public class TestController { @Autowired private MyService myService; @RequestMapping("/test") public String getInedx() throws InterruptedException, ExecutionException, TimeoutException { System.out.println("开始访问"); long l1 = System.currentTimeMillis(); Future<String> r1 = myService.JobOne(); Future<String> r2 = myService.JobTwo(); Future<String> r3 = myService.JobThree(); String result2 = r2.get(50, TimeUnit.MILLISECONDS); System.out.println("使用有参get()获得的返回值"+result2); while(true) {//死循环,每隔2000ms执行一次,判断一下这三个异步调用的方法是否全都执行完了。 if(r1.isDone() && r2.isDone() && r3.isDone()) {//使用Future的isDone()方法返回该方法是否执行完成 //若是异步方法所有执行完,跳出循环 break; } Thread.sleep(2000);//每隔2000毫秒判断一次 } long l2 = System.currentTimeMillis();//跳出while循环时说明此时三个异步调用的方法都执行完成了,此时获得当前时间 String result = r1.get(); /* * String result2 = r2.get(50, TimeUnit.MILLISECONDS); System.out.println("使用有参get()获得的返回值"+result2); 最开始在实验的时候把这两句话放在了这里,就一直测试不出来超时异常, 后来才发现把超时设置在while循环判断已经任务完成以后,那么超时设置固然就不起做用了, 因此放在这里也就不会出现超时异常,应该放在while循环以前即在任务开始执行以后就对其执行时长进行超时设置才会对时间真正起到限制做用。 */ System.out.println("结束访问,用时"+(l2-l1)); System.out.println("使用get方法得到的返回内容:"+result); return "finished"; } }
service中只是改变了一下线程的睡眠时间,让其超过咱们设置的时间:
此时执行的结果就是出现TimeOut异常,且异常Message是null。
那么为何在任务二超时了以后仍然会打印输出任务二方法中的那句用时呢?个人理解是抛出异常的只是get()方法,而任务二线程自己并不受get方法异常的影响,由于get()是在controller这个方法中的另外一个线程,因此任务二会正常执行它的任务,只是get()在检测时本身自己设置超时的行为让它出现了异常。从而,在controller这个线程中出现了异常以后,那么get()以后的语句就再也不执行,因此后面的三个方法异步调用总时长的这些语句都没有被执行也就没有打印输出。