我正在处理 Java 中的多线程,正如有人向我指出的那样,我注意到线程会升温,也就是说,它们会随着重复执行而变得更快。我想了解为什么会发生这种情况,以及它是否与 Java 本身有关,或者它是否是每个多线程程序的常见行为。
示例代码(由 Peter Lawrey 编写)如下:
for (int i = 0; i < 20; i++) {
ExecutorService es = Executors.newFixedThreadPool(1);
final double[] d = new double[4 * 1024];
Arrays.fill(d, 1);
final double[] d2 = new double[4 * 1024];
es.submit(new Runnable() {
@Override
public void run() {
// nothing.
}
}).get();
long start = System.nanoTime();
es.submit(new Runnable() {
@Override
public void run() {
synchronized (d) {
System.arraycopy(d, 0, d2, 0, d.length);
}
}
});
es.shutdown();
es.awaitTermination(10, TimeUnit.SECONDS);
// get a the values in d2.
for (double x : d2) ;
long time = System.nanoTime() - start;
System.out.printf("Time to pass %,d doubles to another thread and back was %,d ns.%n", d.length, time);
}
结果:
Time to pass 4,096 doubles to another thread and back was 1,098,045 ns.
Time to pass 4,096 doubles to another thread and back was 171,949 ns.
... deleted ...
Time to pass 4,096 doubles to another thread and back was 50,566 ns.
Time to pass 4,096 doubles to another thread and back was 49,937 ns.
即它变得更快并稳定在 50 ns 左右。这是为什么?
如果我运行此代码(20 次重复),然后执行其他操作(假设对先前结果进行后处理并为另一轮多线程做准备),然后在相同Runnable
的情况ThreadPool
下再执行 20 次重复,它将已经预热,在任何情况?
在我的程序中,我Runnable
只在一个线程中执行(实际上每个处理核心一个,它是一个 CPU 密集型程序),然后交替执行其他一些串行处理多次。随着程序的进行,它似乎并没有变得更快。也许我可以找到一种方法来加热它……</p>