我正在制作一个多线程应用程序来处理图像,但顺序版本更快,为什么?

时间:2015-05-11 14:56:53

标签: java multithreading bufferedimage

我在线程中使用静态BufferedImage,并让每个线程修改图像的某些部分。处理是非常独立的,因为每个像素是单独完成的,但顺序版本更快,我怎么能解决这个问题呢?

编辑1:这里的代码如何

public static void main(String[] args) throws IOException, InterruptedException {
    long startime, endtime;
    long Time;
    startime = System.currentTimeMillis();
    //also tried to use nano

    WorkingThread T1 = new WorkingThread("input.jpg");
    WorkingThread T2 = new WorkingThread();
    WorkingThread T3 = new WorkingThread();
    WorkingThread T4 = new WorkingThread();

    T1.start();
    T2.start();
    T3.start();
    T4.start();

    T1.join();
    T2.join();
    T3.join();
    T4.join();

    endtime = System.currentTimeMillis();
    Time = endtime - startime;
    System.out.println("The time consumed in miliseconds is  " + Time);
}

public class WorkingThread extends Thread {

  public static BufferedImage img;
  public static int p;
  public int nb;
  public static int width, height;

  public WorkingThread(String file) throws IOException {
    File f = new File(file);
    img = ImageIO.read(f);
    width = img.getWidth();
    height = img.getHeight();
    p = 1;
    nb = 0;
}

  public WorkingThread() {
    nb = p;
    p++;
}

  public void run() {

    int start=nb*height/p;
    int end = (nb + 1) * height/p;
    //the image will be split according to y axis in this case
    for(y=start; y < end ; y++) {
       for(x =0; x<width; x++) {
            pixel = img.getRGB(x, y);
            //processing
            img.setRGB(x, y, pixel);
        }
  }
}

1 个答案:

答案 0 :(得分:1)

正如评论已经指出的那样,您的基准测试中的缺陷是线程设置和拆卸的开销大于按顺序执行代码所花费的时间

插入一些需要花费大量时间的愚蠢代码,如下所示:

//processing
for (int i = 0; i < 1000; i++) {
    pixel = ((~pixel ^ pixel) | pixel) & pixel;
}

...在for x / y循环内并增加i的最大值,您会看到最终多线程版本将比顺序的。

PS:我使用的图像大约是2500 x 3300像素。