gpt4 book ai didi

java - 测量多个线程的执行时间

转载 作者:行者123 更新时间:2023-11-29 04:50:18 25 4
gpt4 key购买 nike

我想测量完整的执行时间(所以当所有线程都完成时)。System.currentimeMillis 的技巧在这里不起作用,因为当 main-method 结束时,我自己创建的线程仍将运行,因为它们比 main-method 需要更长的时间来处理。我该怎么做?

我举个例子。

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.
}
}

最佳答案

您可以使用 ExecutorService :

long startTime = System.nanoTime();
ExecutorService executorService = Executors.myPool();
for(conditions)
executorService.submit(new myThread());

那么别忘了shutdown() :

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

executorService.shutdown();

wait :

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

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);

关于java - 测量多个线程的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com