问题
After execution of below code I am getting time as 0 , because time calculation is present in main thread and it is calculating durationTime value and then executing threadPool.
I wants to find total time taken while executing threads.
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);
}
回答1:
Use awaitTermination after calling shutdown(), which blocks the main thread until all threads finished.
Example:
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;
}
来源:https://stackoverflow.com/questions/27902200/how-can-i-find-execution-time-of-multi-threaded-application