先把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实例。

相关文章:

  • 2021-08-31
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2021-05-25
猜你喜欢
  • 2022-01-09
  • 2021-07-26
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案