我们有这样一个场景。大家看一下是并行执行好,还是串行执行好。
在某平台注册用户 1需要接受邮件 2需要接受短信验证码。3 需要看一段短视频。
我们这个实现需要选择并行执行。没有必要让用户一一做等待。
我们下面通过线程休眠的形式来模拟,在线程休眠的时候其他线程也可以获得调度执行。
1 在启动类中加入@EnableAsync //开启异步任务
package com.zxf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableAsync //开启异步任务
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2 编写异步处理的线程类
package com.zxf.task;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
@Component //开启扫描
@Async //异步。如果没有就是普通类,就不能完成并行执行动作。
public class AsyncTack {
public void task1(){
try{
Thread.sleep(4000);
}catch (Exception e){
}
System.out.println("task1...");
}
public void task2(){
try{
Thread.sleep(4000);
}catch (Exception e){
}
System.out.println("task2....");
}
public void task3(){
try{
Thread.sleep(4000);
}catch (Exception e){
}
System.out.println("task3....");
}
//可以在处理异步请求的时候,返回一些对象
public Future<String> task4(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task4........ ");
return new AsyncResult<String>("task4");
}
//可以在处理异步请求的时候,返回一些对象
public Future<String> task5(){
try{
Thread.sleep(4000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("task5....");
return new AsyncResult<String>("task5");
}
}
3编写一个controller类
@RestController
@RequestMapping("/api/v1/test")
@PropertySource("classpath:pay1.properties")
public class TestController {
@Autowired
private AsyncTack asyncTack;
@GetMapping("async")
public JsonData testAsync(){
long begin=System.currentTimeMillis();
/*
asyncTack.task1();
asyncTack.task2();
asyncTack.task3();
*/
Future<String>task4=asyncTack.task4();
Future<String>task5 = asyncTack.task5();
while (true){
if (task4.isDone() && task5.isDone()){//是否完成
try {
String s4 = task4.get();
System.out.println("我是s4:"+s4);
String s5 = task5.get();
System.out.println("我是s5:"+s5);
}catch (Exception e){
}finally {
break;
}
}
}
long end=System.currentTimeMillis();
return JsonData.buildSuccess(end-begin);//可以计算一下执行了多少毫秒
}
}
运行以后最后的输出时间为并行结果。如果把AsyncTack类的异步取消,就是普通类了。大家在看看执行时间,是否为串行执行了。