先把longTimeMethod 封装到Spring的异步方法中,这个异步方法的返回值是Future的实例。这个方法必定要写在Spring管理的类中,注意注解@Async。java
@Service public class AsynchronousService{ @Async public Future springAsynchronousMethod(){ Integer result = longTimeMethod(); return new AsyncResult(result); } }
其余类调用这个方法。这里注意,必定要其余的类,若是在同类中调用,是不生效的。spring
@Autowired private AsynchronousService asynchronousService; public void useAsynchronousMethod(){ Future future = asynchronousService.springAsynchronousMethod(); future.get(1000, TimeUnit.MILLISECONDS); }
其实Spring只不过在原生的Future中进行了一次封装,咱们最终得到的仍是Future实例。异步