JAVA计算多线程的执行总时间

代码:

ExecutorService exec = Executors.newCachedThreadPool();
long start = System.nanoTime();

System.out.println("kaishi");
for (int i = 0; i < 3; i++){
    exec.execute(new SlsPredictor(args) );
}
exec.shutdown();
exec.awaitTermination(1, TimeUnit.HOURS); // 或者更长时间(这行代码是关键)  
long time = System.nanoTime() - start;
System.out.printf("Tasks took %.3f ms to run%n", time/1e6);

分析:
最关键的代码是:exec.awaitTermination(1, TimeUnit.HOURS);
awaitTermination()函数的源码是:

/**
 * Blocks until all tasks have completed execution after a shutdown
  * request, or the timeout occurs, or the current thread is
  * interrupted, whichever happens first.
  *
  * @param timeout the maximum time to wait
  * @param unit the time unit of the timeout argument
  * @return true if this executor terminated and
  *         false if the timeout elapsed before termination
  * @throws InterruptedException if interrupted while waiting
  */
 boolean awaitTermination(long timeout, TimeUnit unit)
     throws InterruptedException;

从注释可以知道:该函数所在线程会陷入阻塞,直到shutdown请求发出导致所有线程都结束、或者时间超时、或者当前线程被中断,这三个条件只要发生一个,线程就会跳出阻塞状态。
加上了这行,main线程就会阻塞,后面计算执行时间的代码无法执行。直到所有线程执行结束或者到了一个小时(我的参数),才能计算时间。从而达到目的。

你可能感兴趣的:(java线程,多线程,计算时间,java)