如何统计所有线程执行耗时

想法一:在 main 线程中打印当前时间,设置一个守护线程,在所有线程结束后获取当前时间减去初始时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Test {
public static void main(String[] args) throws InterruptedException {
// 初始时间
final long start = System.currentTimeMillis();
Thread daemon = new Thread(() ->
System.out.println("所有线程执行耗时(ms):" + (System.currentTimeMillis() - start)));

daemon.setDaemon(true);
daemon.start();

for (int i = 0; i < 10; i++) {
new Thread(() -> {
//do something
long count = 0;
for (int j = 0; j < 90000000; j++){
count+=j;
}
System.out.println("count="+count);
}).start();
}

}
}

想法二:使用线程的 join() 方法,统计 main 线程从开始到结束的时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Test {
public static void main(String[] args) throws InterruptedException {

long start = System.currentTimeMillis();
List<Thread> threads = new ArrayList<>();

for (int i = 0; i < 10; i++) {
Thread t = new Thread(() -> {
long count = 0;
for (int j = 0; j < 90000000; j++) {
count += j;
}
System.out.println("count=" + count);
}, "thread" + i);
threads.add(t);
t.start();
}

for (Thread t : threads) {
t.join();
}

long end = System.currentTimeMillis();
System.out.println("所有线程执行耗时(ms):" + (end - start));

}
}

想法三:使用 java.util.concurrent 包下的同步辅助类 CountDownLatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Test {
public static void main(String[] args) throws InterruptedException {

final CountDownLatch latch = new CountDownLatch(10);

long start = System.currentTimeMillis();

for (int i = 0; i < 10; i++) {
new Thread(() -> {
long count = 0;
for (int j = 0; j < 90000000; j++) {
count += j;
}
System.out.println("count=" + count);
latch.countDown();
}).start();
}

latch.await();// 当前线程阻塞

System.out.println("所有线程执行耗时(ms):" + (System.currentTimeMillis() - start));

}
}