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 <tt>true</tt> if this executor terminated and
  *         <tt>false</tt> if the timeout elapsed before termination
  * @throws InterruptedException if interrupted while waiting
  */
 boolean awaitTermination(long timeout, TimeUnit unit)
     throws InterruptedException;

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

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值