许久之前就接触Spring异步任务了,通过@Asyns注解标示一个异步任务,再通过配置类@EnableAsyns开启Spring异步支持即可实现简单的异步案例,但是对于带返回值的异步任务则无法通过这种简单的方法实现,此时需要异步方法返回Future对象,而获取的方法也有所不同,需要调用Future对象的get方法,这类似于通过Callable接口实现多线程(其实可以断定其底层就是基于Callable接口),废话不多说直接上代码。
定义异步的业务方法:
// 异步方法
@Async
public Future<String> getStr2()
{
try
{
// 模拟延迟
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return new AsyncResult<>("返回值");
}
// 返回集合类型
@Async
public Future<List<String>> getStr3()
{
List<String> list=new ArrayList<>();
try
{
// 模拟延迟
Thread.sleep(1000);
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
} catch (InterruptedException e)
{
e.printStackTrace();
}
return new AsyncResult<>(list);
}
获取异步任务返回值:
// 获取字符串返回值
@GetMapping("test2")
public Object test2() throws Exception
{
Future<String> future = emailUtils.getStr2();
return future.get();
}
// 常规的获取方法,会返回空
@GetMapping("test3")
public Object test3()
{
return emailUtils.getStr2();
}
// 获取集合类型
@GetMapping("test4")
public Object test4() throws Exception
{
Future<List<String>> future = emailUtils.getStr3();
return future.get();
}
既然话都说到这里了,就再复习下Callable接口吧:
package com.lsm1998.test.Thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableTest implements Callable<String>
{
@Override
public String call() throws Exception
{
Thread.sleep(1000);
return "hello";
}
public static void main(String[] args) throws Exception
{
FutureTask<String> task = new FutureTask<>(new CallableTest());
Thread thread = new Thread(task);
thread.start();
System.out.println("执行到此");
System.out.println("返回值=" + task.get());
// lambda表达式实现
FutureTask<String> task2 = new FutureTask<>(() -> "你好");
new Thread(task2).start();
System.out.println("执行到此");
System.out.println("返回值=" + task2.get());
}
}