有时候咱们须要展现一些内容,若是等全部内容都加载完毕再展现这样反而会下降用户体验;
由于若是消耗时间长那么用户须要瞪着空白的页面,反而会失去兴趣;
因此咱们但愿加载一点资源显示一点,对于那么超过咱们容忍范围还未加载完毕的资源咱们应该
再也不去加载,放弃本次加载或者显示一些默认结果dom模拟:ide
final Random r = new Random(); // 建立一个固定大小的线程池 ExecutorService es = Executors.newFixedThreadPool(10); // 将全部处理结果提交到一个固定大小的队列(可不指定,默认建立一个无界队列) ExecutorCompletionService<String> ecs = new ExecutorCompletionService<String>( es,new LinkedBlockingQueue<Future<String>>(1000)); for (int i = 0; i < 10; i++) { //提交全部任务 ecs.submit(new Callable<String>() { @Override public String call() throws Exception { //模拟一个耗时操做 long l = r.nextInt(4000); Thread.sleep(l); return Thread.currentThread().getName() + "|" + l; } }); try { //得到返回结果,3s超时(表示咱们可以容忍的最大等待时间) System.out.println(ecs.take().get(3, TimeUnit.SECONDS)); } catch (InterruptedException e) { // 线程被中断 } catch (ExecutionException e) { // e.printStackTrace(); } catch (TimeoutException e) { // 超时,放弃这个结果 } } es.shutdown();pool-1-thread-1|884 pool-1-thread-2|3469 pool-1-thread-3|1001 pool-1-thread-4|927 pool-1-thread-5|3503 pool-1-thread-6|712 pool-1-thread-7|2015 pool-1-thread-8|2430 pool-1-thread-9|1613 pool-1-thread-10|2583