在多个线程中测量执行时间

4
我希望测量完整的执行时间(即当所有线程都完成时)。 使用 System.currentimeMillis 的方法在这里行不通,因为当主方法结束时,我创建的线程仍在运行,因为它们需要比主方法更长的时间来处理。 我该怎么做呢?
我来举个例子。
public class Main {

public static void main(String[] args) {

    long start = System.currentTimeMillis();

    new Thread(() -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();

    long end = System.currentTimeMillis();

    System.out.println(end - start); // Won't work because my new Thread will still be running here.
}
}
2个回答

4
您可以使用一个ExecutorService来处理相关的IT技术。
long startTime = System.nanoTime();
ExecutorService executorService = Executors.myPool();
for(conditions)
   executorService.submit(new myThread());

那么不要忘记执行 shutdown() 方法:

该方法会启动一个有序的关闭过程,之前提交的任务将被执行,但是不再接受新的任务。如果已经关闭,则调用没有额外的效果。

executorService.shutdown();

并且等待:

在关闭请求后,或超时发生或当前线程被中断之前,阻塞直到所有任务完成执行。

executorService.awaitTermination(1, TimeUnit.HOUR); // however long you need

然后进行计算:
long totalTime = System.nanoTime() - startTime; 

System.out.printf("The total time everything took was %.3f ms %n", totalTime/1e6);

1

在测量结束时间之前,您应该考虑使用线程连接。这将确保主线程仅在所有其他线程退出时退出。

package threadsync;

public class MeasureRunningTime {

public static void main(String[] args) {

    long start = System.currentTimeMillis();

    Thread th = new Thread(){ 
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
    };

    th.start();

    try {
        th.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long end = System.currentTimeMillis();

    System.out.println("The thread took:" +  (end - start) + "ms");
}

}

在这种情况下,输出应该是:
线程花费时间:5003毫秒

如果有帮助的话,请告诉我。 - The Roy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接