我有以下示例代码。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.*;
public class CalculationThread implements Callable<Long> {
public Long call() throws Exception {
long k=0L;
for(int i=0;i<100000;i++){
for(int j=0;j<50;j++){
k=i+j;
}
}
return k;
}
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(4);
long startTime = System.nanoTime();
for(int lo=0;lo<5000;lo++){
Future<Long> result = executorService.submit(new CalculationThread());
try {
Long l = result.get();
} catch (Exception e) {
result.cancel(true);
}
}
long endTime = System.nanoTime();
System.out.println("Using threads took "+(endTime - startTime) + " ns");
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);
long k=0L;
startTime = System.nanoTime();
for(int lo=0;lo<5000;lo++){
for(int i=0;i<100000;i++){
for(int j=0;j<50;j++){
k=i+j;
}
}
}
endTime = System.nanoTime();
System.out.println("Generally it takes "+(endTime - startTime) + " ns");
}
}
输出分布为
Using threads took 101960490 ns
Generally it takes 143107865 ns
至
Using threads took 245339720 ns
Generally it takes 149699885 ns
可以注意到第二行几乎是不变的,而线程版本变化很大。为什么会出现这种情况?可以做些什么来减少变异性?请让我知道我是否在做一些愚蠢的事情,因为我是 Java 多线程的新手。