一年前,我用 java 7 做了一些关于多核的测试。首先,我仅在主线程中实现了一些计算(CPU 使用情况表明只有一个核心完成了所有工作),然后我使用 ExecutorService 实例实现了 Callable。运行时所有核心都在工作。
现在,一年后,我必须实现一个小程序(使用 java 8)来插入大量数据。所有工作都是在主线程中实现的(没有 Callable 和 ExecutorService),但是当我运行程序时,CPU 使用率显示,所有 4 个核心都处于 98%。
那么java 8会自动将工作分配到所有CPU核心上吗?我很困惑...
这里有一些代码...
地图生成器.java
Region[][] regions = new Region[numOfRegions][numOfRegions];
for(int x = 0; x < regions.length; x++){
for(int z = 0; z < regions[x].length; z++){
newLat = SRTMHandler.getNewLatitude(startLat, z * regionSize * 16);
newLon = SRTMHandler.getNewLongitude(startLon, x * regionSize * 16, newLat);
regions[x][z] = new Region(x, z, regionSize, newLat, newLon);
}
}
区域.java:
private Chunk[] chunks;
public Region(int x, int z, int size, float startLat, float startLon){
this.chunks = new Chunk[this.size][this.size];
//Init stuff
float newLat = this.startLat, newLon = this.startLon;
for(int newX = 0; newX < this.size; newX++){
for(int newZ = 0; newZ < this.size; newZ++){
newLat = SRTMHandler.getNewLatitude(this.startLat, newZ * 16);
newLon = SRTMHandler.getNewLongitude(this.startLon, newX * 16, newLat);
this.chunks[newX][newZ] = new Chunk(this.x * this.size + newX, this.z * this.size + newZ, 16, 900, this, newLat, newLon);
}
}
}
Chunk.java:(SRTMHandler.getHeightForLatLon() 进行一些地理计算,然后读取字节数组中的值,没什么特别的)
public Chunk(int x, int z, int size, int height, Region r, float startLat, float startLon){
this.blocks = new Block[size][size][height];
//Init stuff
try {
this.calcSurface();
//System.out.println("Finished " + this.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void calcSurface() throws IOException{
int x1 = this.x;
int x2 = this.x + 16;
int z1 = this.z;
int z2 = this.z + 16;
final int radius = 45;
float q11 = SRTMHandler.getHeightForLatLon(SRTMHandler.getNewLatitude(this.startLat, (-1)*radius), SRTMHandler.getNewLongitude(this.startLon, (-1)*radius, this.startLat));
float q12 = SRTMHandler.getHeightForLatLon(SRTMHandler.getNewLatitude(this.startLat, radius), SRTMHandler.getNewLongitude(this.startLon, (-1)*radius, this.startLat));
float q21 = SRTMHandler.getHeightForLatLon(SRTMHandler.getNewLatitude(this.startLat, (-1)*radius), SRTMHandler.getNewLongitude(this.startLon, radius, this.startLon));
float q22 = SRTMHandler.getHeightForLatLon(SRTMHandler.getNewLatitude(this.startLat, radius), SRTMHandler.getNewLongitude(this.startLon, radius, this.startLat));
for(int x = 0; x < this.blocks.length; x++){
for(int z = 0; z < this.blocks[x].length; z++){
float height = Interpolation.biLerp(x, z, q11, q12, q21, q22, x1, x2, z1, z2);
this.blocks[x][z][(int)Math.round(height)] = new Block(this.x * this.size + x, this.z * this.size + z, (int)Math.round(height), BlockType.Grass, this);
}
}
}