ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 60,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
Random random = new Random();
ArrayList<Future> arrayList = new ArrayList<Future>();
long st = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Call call = new Call();
call.setI(i);
call.setSleepTime(random.nextInt(10000));
Future future = executor.submit(call);
arrayList.add(future);
}
System.out.println(System.currentTimeMillis() - st);
st = System.currentTimeMillis();
int totalTime = 0;
for (Future future : arrayList) {
try {
totalTime += (Integer)future.get();
System.out.println("totalTime="+totalTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("END="+(System.currentTimeMillis() - st));
从上面的代码可以看到,totalTime 是同步执行时所需要消耗的时间;END值为最终执行需要的时间。
END值其实基本上就是队列满时执行最长时间的那个任务,简单计算的话,近似=所有任务数/corepoolsize*平均最大任务执行时间。
呵呵,个人理解,小记一下。
本文通过一个具体的Java线程池实现案例,介绍了线程池的执行机制及其关键参数的作用。通过对不同任务的并发处理过程进行分析,展示了线程池如何有效管理任务队列和线程资源。
484

被折叠的 条评论
为什么被折叠?



