并发的实现以及结果获取
并发即多个线程同时进行任务,即异步任务,以下例子测试了并发进行四个任务,并同时返回结果的案例。
service层
@Service
public class AsyncTest {
@Async
public Future<Boolean> doReturn1(){
try {
// 这个方法需要调用500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("一号线程:"+i);
}
// 消息汇总
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doReturn2(){
try {
// 这个方法需要调用500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("二号线程:"+i);
}
// 消息汇总
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doReturn3(){
try {
// 这个方法需要调用500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("三号线程:"+i);
}
// 消息汇总
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doReturn4(){
try {
// 这个方法需要调用500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("四号线程:"+i);
}
// 消息汇总
return new AsyncResult<>(true);
}
}
controller层
@RequestMapping("/async")
public String async(){
List<Future<Boolean>> futures = new ArrayList<>();
Future<Boolean> flag1 = asyncTest.doReturn1();
Future<Boolean> flag2 = asyncTest.doReturn2();
Future<Boolean> flag3 = asyncTest.doReturn3();
Future<Boolean> flag4 = asyncTest.doReturn4();
futures.add(flag1);
futures.add(flag2);
futures.add(flag3);
futures.add(flag4);
List<Boolean> response = new ArrayList<>();
for (Future future : futures) {
Boolean flag = null;
try {
flag = (Boolean) future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
response.add(flag);
}
System.out.println(response);
return response.toString();
}
这种方法即可在并发的时候拦截到全部完成后的结果进行判断,满足才进行下一步。