我正在尝试 Java ForkJoin 框架并编写了一个简单的测试程序,将图像的像素设置为随机颜色。例如,它会产生伪噪声。
但是在测试性能时,我发现运行单线程实际上比使用多线程运行更快。我通过一个高阈值让它运行单线程。
这是阶级工人阶级:
public class Noise extends RecursiveAction {
private BufferedImage image;
private int xMin;
private int yMin;
private int xMax;
private int yMax;
private int threshold = 2000000; // max pixels per thread
public Noise(BufferedImage image, int xMin, int yMin, int xMax, int yMax, int threshold) {
this.image = image;
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.threshold = threshold;
}
public Noise(BufferedImage image, int xMin, int yMin, int xMax, int yMax) {
this.image = image;
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
}
@Override
protected void compute() {
int ppt = (xMax - xMin) * (yMax - yMin); // pixels pet thread
if(ppt > threshold) {
// split
int verdeling = ((xMax - xMin) / 2) + xMin;
invokeAll(new Noise(image, xMin, yMin, verdeling, yMax),
new Noise(image, verdeling+1, yMin, xMax, yMax));
}
else {
// execute!
computeDirectly(xMin, yMin, xMax, yMax);
}
}
private void computeDirectly(int xMin, int yMin, int xMax, int yMax) {
Random generator = new Random();
for (int x = xMin; x < xMax; x++) {
for (int y = yMin; y < yMax; y++) {
//image.setPaint(new Color(generator.nextInt()));
int rgb = generator.nextInt();
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
red = (int) Math.round((Math.log(255L) / Math.log((double) red)) * 255);
green = (int) Math.round((Math.log(255L) / Math.log((double) green)) * 255);
blue = (int) Math.round((Math.log(255L) / Math.log((double) blue)) * 255);
int rgbSat = red;
rgbSat = (rgbSat << 8) + green;
rgbSat = (rgbSat << 8) + blue;
image.setRGB(x, y, rgbSat);
}
}
Graphics2D g2D = image.createGraphics();
g2D.setPaint(Color.RED);
g2D.drawRect(xMin, yMin, xMax-xMin, yMax-yMin);
}
}
生成 6000 * 6000 图像时,结果为:
单线程:9.4 秒 @ 25% CPU 负载
多线程:16.5 秒 @ 80%-90% CPU 负载
(Core2quad Q9450)
为什么多线程版本比较慢?
我该如何解决?