可能重复:
“Parallel.For” for Java?
.NET具有Parallel.For,它允许您并行运行for循环,而无需直接使用线程。
Java中有类似的东西吗?我找到了完全相同的问题(Here),但是在最新版本的Java出现之前就被问到了,它声称有:
“JSR 166下的并发实用程序”
那么,他们放了什么东西吗?
答案 0 :(得分:3)
虽然可以建议Parallel.For与ExecutorService.submit类似,但我怀疑它不是。
public static void main(String... args) throws InterruptedException {
long start1 = System.nanoTime();
int runs1 = 1000;
final int[] a = new int[100];
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < 100; i++) {
a[i] = a[i] * a[i];
}
}
long time1 = System.nanoTime() - start1;
System.out.printf("Each loop took an average of %,d micro-seconds%n", time1 / runs1 / 1000);
int processors = Runtime.getRuntime().availableProcessors();
long start2 = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(processors);
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < 100; i++) {
final int i2 = i;
executor.submit(new Runnable() {
public void run() {
a[i2] = a[i2] * a[i2];
}
});
}
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
long time2 = System.nanoTime() - start2;
System.out.printf("Parallel: Each loop took an average of %,d micro-seconds%n", time2 / runs1 / 1000);
}
打印
Each loop took an average of 2 micro-seconds
Parallel: Each loop took an average of 149 micro-seconds
这表明在这个例子中,使用多个线程是非常糟糕的主意。所以我希望循环效率稍高一些
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < processors; i++) {
final int i2 = i;
executor.submit(new Runnable() {
public void run() {
for (int i3 = i2 * 100 / processors; i3 < (i2 + 1) * 100 / processors && i3 < 100; i3++)
a[i2] = a[i2] * a[i2];
}
});
}
}
打印
Parallel: Each loop took an average of 28 micro-seconds
如果你认为Runnable中的代码不是线程安全的,我怀疑Parallel.For做了一些相当不同的事情,或者说它毫无意义。
答案 1 :(得分:1)
Fork / Join Framework应该包含在Java 8中,还有lambdas / closures ......最近,Java冠军之一Angelika Langer就这个主题发表了很好的演讲
答案 2 :(得分:1)
我的并行计算教授Alan Kaminsky和他的一群研究生已经编写了一个具有您所需功能的库。
信息页面涵盖了Javadocs,许可证,下载,甚至免费书籍。
它是GNU GPL版本3下的自由软件。