指定时间获取广告信息FutureTask

Page renderPageWithAd() throws InterruptedException{
    
    
  long endNanos = System.nanoTime+TIME_BUGET;
  Future<AD> f = exec.submit(new FetchAdTask());
  //等待广告的同时渲染页面
  Page page = renderPageBody();
  Ad ad;
  try{
    
    
    //只等待指定的时间长度
    long timeLeft = endNanos - System.nanoTime();
    ad = f.get(timeLeft,NANOSECONDS);
  }catch(ExecutionException e){
    
    
    ad = DEFAULT_AD;
  }catch(TimeoutException e){
    
    
    ad = DEFAULT_AD;
    f.cancel(true);
  }
  page.setAd(ad);
  return page;
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118248621