java---18

目录

一  同步调用和异步调用的区别

二  导入Async依赖

三  开启异步调用

四  示例代码


一  同步调用和异步调用的区别

同步调用:同步调用是一种阻塞式调用,一段代码调用另一端代码时,必须等待这段代码执行结束并返回结果后,代码才能继续执行下去;

异步调用:异步调用是一种非阻塞式调用,一段异步代码还未执行完,可以继续执行下一段代码逻辑,当代码执行完以后,通过回调函数返回继续执行相应的逻辑,而不耽误其他代码的执行。

二  导入Async依赖

无需加入额外依赖;

三  开启异步调用

在项目的启动类上添加@EnableAsync注解即可;

 
@SpringBootApplication
 
@EnableScheduling
 
@EnableAsync
 
public class SpringbootexampleApplication {
 
 
 
public static void main(String[] args) {
 
SpringApplication.run(SpringbootexampleApplication.class, args);
 
}
 
 
 
}

 

四  示例代码

同步方法执行时间

 
@Component
 
public class MySyncTask {
 
 
 
public void task1() throws InterruptedException {
 
long T1 = System.currentTimeMillis();
 
Thread.sleep(2000);
 
long T2 = System.currentTimeMillis();
 
System.out.println("task1消耗时间"+(T2-T1)+"ms");
 
}
 
 
 
public void task2() throws InterruptedException {
 
long T1 = System.currentTimeMillis();
 
Thread.sleep(3000);
 
long T2 = System.currentTimeMillis();
 
System.out.println("task2消耗时间"+(T2-T1)+"ms");
 
}
 
}
方法调用 

 
@RequestMapping("syncTask")
 
public void syncTask() throws InterruptedException {
 
long l1 = System.currentTimeMillis();
 
mySyncTask.task1();
 
mySyncTask.task2();
 
long l2 = System.currentTimeMillis();
 
System.out.println("执行同步消耗时间"+(l2-l1)+"ms");
 
 
 
}

 

运行结果 

 

异步方法执行时间

 
@Component
 
public class MyAsyncTask {
 
 
 
@Async
 
public void task1() throws InterruptedException {
 
long T1 = System.currentTimeMillis();
 
Thread.sleep(2000);
 
long T2 = System.currentTimeMillis();
 
System.out.println("task1消耗时间"+(T2-T1)+"ms");
 
}
 
 
 
@Async
 
public void task2() throws InterruptedException {
 
long T1 = System.currentTimeMillis();
 
Thread.sleep(3000);
 
long T2 = System.currentTimeMillis();
 
System.out.println("task2消耗时间"+(T2-T1)+"ms");
 
}
 
}

 

方法调用 

 
@RequestMapping("asyncTask")
 
public void asyncTask() throws InterruptedException {
 
long l1 = System.currentTimeMillis();
 
myAsyncTask.task1();
 
myAsyncTask.task2();
 
long l2 = System.currentTimeMillis();
 
System.out.println("执行异步消耗时间"+(l2-l1)+"ms");
 
 
 
}

 

运行结果 

posted @ 2020-12-31 12:01  ぁ晴  阅读(76)  评论(0)    收藏  举报