我想测量完整的执行时间(所有线程完成时)。 但是我的代码在这里行不通,因为当主方法结束时,其他线程仍在运行,因为它们比主方法花费的时间更长。
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()
来测量在单线程v / s多线程上运行程序时的执行时间。
答案 0 :(得分:6)
只需在hello.join()
之后添加hi.join()
和hi.start()
您最好使用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
,它们也被执行。
答案 1 :(得分:4)
使用join()
将停止代码进入下一行,直到线程死亡为止。
public static void main(String[] args) {
final Hello hello = new Hello();
final Hi hi = new Hi();
final long startTime = System.nanoTime();
hello.start();
hi.start();
try{
hello.join();
hi.join();
}
catch(InterruptedException e){}
final long time = System.nanoTime() - startTime;
System.out.println("time to execute whole code: " + time);
}