可并行化的算法:某个CPU上运行循环的迭代的同时,另一个CPU上运行另一个循环的迭代。之间数据的依赖性可能会禁止某特定的循环被并行化,但是对于CPU密集的程序,将可能的循环并行化可以大幅提高程序运行速度。(by Johnny Deng)
Java的编译器不支持循环并行的自动化,但是我们可以了手动的实现一下。举例:
原程序:
/*-**************************************************************/
*
* Package Name: seibuaa.concurrency
* File Name; PowerTable.java
* Description :
* Author : DengXiong
* Copyright : SEI BUAA
* Date : 2006-10-20
*
/*-**************************************************************/
package seibuaa.concurrency;
public class CosTable {
private volatile double CosTable[] = null;
public synchronized double[] getValues(){
if (this.CosTable == null) return CosTable = new double[100*100];
for (int i = 0; i < 100*100; i++){
double cosValue = (double)Math.cos(i % 360) * Math.PI / 180.0;
this.CosTable[i] = cosValue * (double)i / 180.0d;
}
return this.CosTable;
}
}
修改后的程序:
/*-**************************************************************/
*
* Package Name: seibuaa.concurrency
* File Name; CosTableConCurrency.java
* Description :
* Author : DengXiong
* Copyright : SEI BUAA
* Date : 2006-10-20
*
/*-**************************************************************/
package seibuaa.concurrency;
public class CosTableConCurrency implements Runnable{
private class CosTableRanges{
public int start, end;
}
private volatile double cosTable[];
private int startLoop, curLoop, endLoop, numThreads;
private Thread cosThread[];
public CosTableConCurrency(){
this.cosTable = new double[100 * 100];
this.cosThread = new Thread[10];
startLoop = curLoop = 0;
endLoop = 100*100;
numThreads = 10;
}
public synchronized CosTableRanges loopGetRange(){
if (this.curLoop > this.endLoop) return null;
CosTableRanges ret = new CosTableRanges();
ret.start = curLoop;
curLoop += (endLoop - startLoop)/numThreads + 1;
ret.end = (curLoop < endLoop) ? curLoop:endLoop;
return ret;
}
public void loopDoRange(int start, int end){
for (int i = start; i < end; i ++){
double cosValue = (double)Math.cos(i % 360) * Math.PI / 180.0;
this.cosTable[i] = cosValue * (double)i / 180.0d;
}
}
public void run() {
CosTableRanges ctr;
while ((ctr = loopGetRange()) != null){
loopDoRange(ctr.start, ctr.end);
}
}
public double[] getValues(){
for (int i = 0; i < 100 * 100; i++){
this.cosThread[i] = new Thread(this);
this.cosThread[i].start() ;
}
for (int i = 0; i < 100 * 100; i++){
try {
this.cosThread[i].join() ;
}catch (InterruptedException e){
}
}
return this.cosTable;
}
}
至于关于调度的策略与负载平衡等高级问题,就掠过了!:)
2256

被折叠的 条评论
为什么被折叠?



