我想测量完整的执行时间(当所有线程完成时)。 但我的代码在这里不起作用,因为当主方法结束时,其他线程仍将运行,因为它们比主方法需要更长的处理时间。
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
通常执行 Runnable
或 Callable
,但由于 Thread
正在扩展 Runnable
它们也会被执行。
关于java - 多线程java的完整执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862371/