【发布时间】:2015-08-05 19:20:00
【问题描述】:
我有以下示例代码。
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 多线程的新手。
【问题讨论】:
-
您将 4 个初始线程添加到可用的 4 个线程中,并将剩余的 4996 个操作添加到线程池中,这与较短的总执行时间相比效率并不高
~149 ms (General execution).线程在time > 2 s min中将非常有用,并尝试减少线程池中的队列数。
标签: java multithreading callable java-threads