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) + "毫秒");
}
}