Spring的异步方法

先把longTimeMethod 封装到Spring的异步方法中,这个异步方法的返回值是Future的实例。这个方法一定要写在Spring管理的类中,注意注解@Async。

@Service
public class AsynchronousService{ @Async public Future springAsynchronousMethod(){ Integer result = longTimeMethod(); return new AsyncResult(result); } }

其他类调用这个方法。这里注意,一定要其他的类,如果在同类中调用,是不生效的。

@Autowired
private AsynchronousService asynchronousService;

public void useAsynchronousMethod(){ Future future = asynchronousService.springAsynchronousMethod(); future.get(1000, TimeUnit.MILLISECONDS); }

其实Spring只不过在原生的Future中进行了一次封装,我们最终获得的还是Future实例。

猜你喜欢

转载自www.cnblogs.com/austinspark-jessylu/p/11038701.html