执行下面的代码后,我得到时间为0,因为主线程中存在时间计算,它正在计算durationTime值然后执行threadPool。
我想找到执行线程所花费的总时间。
public static void main(String[] args) {
long startTime = System.nanoTime();
int numberThread=10;
String apiToBeCall="abcApi";
Runnable r1=new SFSrmMainClass(apiToBeCall);
ExecutorService threadPool=Executors.newFixedThreadPool(numberThread);
for (int i=0;i<numberThread;i++)
{
threadPool.execute(r1);
}
threadPool.shutdown();
long endTime = System.nanoTime();
long durationTime = (endTime - startTime);
System.out.println("time for "+apiToBeCall +" is having thread="+numberThread +" is "+durationTime/1000000000);
}
答案 0 :(得分:0)
在调用shutdown()之后使用awaitTermination,这会阻塞主线程直到所有线程都完成。
示例:
static long measureTasks(final int nThreads, final Runnable... tasks)
throws InterruptedException
{
final ExecutorService pool = Executors.newFixedThreadPool(nThreads);
final long startTime = System.nanoTime();
for (Runnable task : tasks)
pool.execute(task);
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
return System.nanoTime() - startTime;
}