如何计算多个线程完成执行所需的总时间?

use*_*803 5 java multithreading response runnable

我从我的代码开始多个线程(大约1000个).它们是从while循环调用的Runnable线程.如何计算所有线程完成执行所需的总时间?

此外,我打开一个数据库连接,并有一组查询,我正在启动这些线程(1个查询的1个线程).我什么时候关闭连接?

Pet*_*rey 8

我会使用ExecutorService

long start = System.nanoTime();
ExecutorService service = Executors.newWhatEverPool();
for(loop)
   service.submit(new MyRunnable());

service.shutdown();
service.awaitTermination(1, TimeUnit.HOUR); // or longer.    
long time = System.nanoTime() - start;
System.out.printf("Tasks took %.3f ms to run%n", time/1e6);
Run Code Online (Sandbox Code Playgroud)

完成后关闭连接.对于资源的创建者来说,关闭它也是一种常见的模式.例如,如果主线程创建连接,它可能在所有线程完成后关闭.