有时候我们需要展示一些内容,如果等所有内容都加载完毕再展示这样反而会降低用户体验; 因为如果消耗时间长那么用户需要瞪着空白的页面,反而会失去兴趣; 所以我们希望加载一点资源显示一点,对于那么超过我们容忍范围还未加载完毕的资源我们应该 不再去加载,放弃本次加载或者显示一些默认结果
模拟:
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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有