我正在使用synchronized块在java中创建一个玩具程序。我有n个“Pixelator”线程,它在1000x1000图像中选择一个随机像素并将其分配给Pixelator的颜色。每个像素只能分配一次。我使用包装类写入bufferedImage,该类使用synchronized方法写入图像。但是,当我使用多个线程进行测试时,我看不到加速。你有一个暗示为什么会这样吗?
相对代码:
import java.awt.Color;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.util.ArrayList;
import java.util.Random;
public class q2 {
// The image constructed
public static BufferedImage img;
// Image dimensions; you could also retrieve these from the img object.
public static int width;
public static int height;
// simplified method for stack overflow example
public static int rgbFromN(int n) {
return -16755216;
}
public static void main(String[] args) {
Random r = new Random();
try {
// arg 0 is the width
width = 1000;
// arg 1 is the height
height = 1000;
// arg 2 is the number of threads
int nt = 1;
// create an image and initialize it to all 0's
img = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
synchronizedIMG simg = new synchronizedIMG(img);
for (int i=0;i<width;i++) {
for (int j=0;j<height;j++) {
img.setRGB(i,j,0);
}
}
Thread[] threads = new Thread[nt];
long startTime = System.currentTimeMillis();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Pixelator(rgbFromN(i),width,height,((width*height)/nt),simg));
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
long endTime = System.currentTimeMillis();
System.out.println("Time(ms): " + (endTime-startTime));
// Write out the image
File outputfile = new File("outputimage.png");
ImageIO.write(img, "png", outputfile);
} catch (Exception e) {
System.out.println("ERROR " +e);
e.printStackTrace();
}
}
}
class Pixelator implements Runnable {
int color;
int width;
int height;
int numPixels;
int currentPixels = 0;
synchronizedIMG simg;
public Pixelator(int color, int width, int height,int numPixels, synchronizedIMG simg){
this.color = color;
this.width = width;
this.height = height;
this.numPixels = numPixels;
this.simg = simg;
}
public void run() {
int randomX = 0;
int randomY = 0;
boolean success = false;
while(currentPixels < numPixels){
randomX = 0 + (int)(Math.random() * (width));
randomY = 0 + (int)(Math.random() * (height));
success = simg.setColor(color, randomX, randomY);
if(success){
currentPixels++;
}
}
return;
}
}
class synchronizedIMG{
BufferedImage img;
public synchronizedIMG(BufferedImage img){
this.img = img;
}
public synchronized boolean setColor(int color, int x, int y){
if(img.getRGB(x, y) == 0){
img.setRGB(x, y, color);
return true;
} else{
return false;
}
}
}
答案 0 :(得分:0)
机器需要一定的时间来管理线程。在图像处理中,使用两个线程而不是一个,不会将处理时间减少50%,但根据处理(使用我自己的java库的多线程类进行经验估计),可以减少30%到40个。
此外,在您的情况下,您不需要进行任何主要处理,只需简单的计算。因此管理线程比在单个线程上进行处理要长。试着做一个很大的卷积。
答案 1 :(得分:0)
您面临的最大问题是添加更多线程不会增加系统的内存带宽。
除了计算随机数并将其写入内存之外,您的线程不执行任何操作。添加更多线程可能会提高计算随机数的速度,但这可能是非常快的开始。 Math.random()不是加密质量的随机数生成器。它可能非常快。
不幸的是,在将所有字节写入内存之前,您的工作尚未完成。您的系统只有一个内存总线,它只能这么快。所有线程都必须争用该资源。