我试图对一个简单的Java应用程序进行多线程基准测试,将迭代器的每个元素转换为另一个元素。
在下面的这些方法中(Java 8并行流,使用lambda运算符的常规多线程),哪种方法效率最高?根据下面的输出结果,好像并行流和传统的多线程一样好,是吗?
下面代码(你需要将alice.txt替换为另一个文件)的输出:
153407 30420
时间(毫秒) - 4826
153407 30420
时间(毫秒) - 37908
153407 30420
时间(毫秒) - 37947
153407 30420
时间(毫秒) - 4839
public class ParallelProcessingExample {
public static void main(String[] args) throws IOException{
String contents = new String(Files.readAllBytes(
Paths.get("impatient/code/ch2/alice.txt")), StandardCharsets.UTF_8);
List<String> words = Arrays.asList(contents.split("[\\P{L}]+"));
long t=System.currentTimeMillis();
Stream<String> wordStream = words.parallelStream().map(x->process(x));
String[] out0=wordStream.toArray(String[]::new);
System.out.println(String.join("-", out0).length()+"\t"+out0.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
wordStream = words.stream().map(x->process(x));
String[] out1=wordStream.toArray(String[]::new);
System.out.println(String.join("-", out1).length()+"\t"+out1.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
String[] out2=new String[words.size()];
for(int j=0;j<words.size();j++){
out2[j]=process(words.get(j));
}
System.out.println(String.join("-", out2).length()+"\t"+out2.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
int n = Runtime.getRuntime().availableProcessors();
String[] out3=new String[words.size()];
try {
ExecutorService pool = Executors.newCachedThreadPool();
for(int i=0;i<n;i++){
int from=i*words.size()/n;
int to=(i+1)*words.size()/n;
pool.submit(() -> {
for(int j=from;j<to;j++){
out3[j]=process(words.get(j));
}
});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.HOURS);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(String.join("-", out3).length()+"\t"+out3.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
}
private static String process(String x) {
try {
TimeUnit.NANOSECONDS.sleep(1);
//Thread.sleep(1); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
return x.toUpperCase();
}
}