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*平均最大任务执行时间。
呵呵,个人理解,小记一下。