标签:异步 end Springboot System long currentTimeMillis 响应速度 start public
asynchronous CALL(异步调用)一个可以无需等待被调用函数的返回值就让操作继续进行的方法
1、启动类上添加开启异步注解
@EnableAsync
public class Application {
2、编写异步方法
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.Random;
import java.util.concurrent.Future;
@Component
public class Task {
public static Random random =new Random();
@Async
public Future<Long> doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
return new AsyncResult<>(end-start);
}
@Async
public Future<Long> doTaskTwo() throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
return new AsyncResult<>(end-start);
}
@Async
public Future<Long> doTaskThree() throws Exception {
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
return new AsyncResult<>(end-start);
}
}
3、执行异步调用
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=Application.class)
public class MainTester {
@Resource
private Task task;
@Test
public void test() throws Exception {
long start = System.currentTimeMillis();
Future<Long> task1 = task.doTaskOne();
Future<Long> task2 = task.doTaskTwo();
Future<Long> task3 = task.doTaskThree();
Long res1 = task1.get();
Long res2 = task2.get();
Long res3 = task3.get();
System.out.println("任务1完成耗时:"+res1);
System.out.println("任务2完成耗时:"+res2);
System.out.println("任务3完成耗时:"+res3);
long end = System.currentTimeMillis();
System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
}
}
标签:异步,end,Springboot,System,long,currentTimeMillis,响应速度,start,public 来源: https://blog.csdn.net/qq_36154832/article/details/121081065
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。