gpt4 book ai didi

java - 多线程java的完整执行时间

转载 作者:行者123 更新时间:2023-12-02 05:56:27 25 4
gpt4 key购买 nike

我想测量完整的执行时间(当所有线程完成时)。但我的代码在这里不起作用,因为当主方法结束时,其他线程仍将运行,因为它们比主方法需要更长的处理时间。

class Hello extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
try {
Thread.sleep(500);
} catch (final Exception e) {
}
}
}

}

class Hi extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hi");
try {
Thread.sleep(500);
} catch (final Exception e) {
}
}
}
}

public class MultiThread {
public static void main(String[] args) {
final long startTime = System.nanoTime();
final Hello hello = new Hello();
final Hi hi = new Hi();
hello.start();
hi.start();

final long time = System.nanoTime() - startTime;
System.out.println("time to execute whole code: " + time);

}

}

我试图找到程序在单线程与多线程上运行时的执行时间,使用 System.nanoTime()测量时间。

最佳答案

只需在 hi.start() 之后添加 hello.join()hi.join()

你最好使用ExecutorService:

public static void main(String[] args) {
final long startTime = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Hello());
executor.execute(new Hi());
// finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
executor.awaitTermination();
final long time = System.nanoTime() - startTime;
System.out.println("time to execute whole code: " + time);
}

ExecutorService 通常执行 RunnableCallable,但由于 Thread 正在扩展 Runnable 它们也会被执行。

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

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