对于一个类项目,我们需要采用一个实现Sobel算法的程序,并在多个线程中运行它,以便熟悉线程。我有程序正确地运行程序(据我所知),但每当我使用多个线程实现它时,我看到一个黑色边框沿着分隔区域运行,缓冲区似乎不是写入目的地BufferedImage。
以下是负责线程化和编写文件的方法的一些代码:
public void processImage(int threads)
{
try{
File imgFile = new File(bmpFile);
image = ImageIO.read(imgFile);
w = image.getWidth();
wThr = (image.getWidth()/threads);
h = image.getHeight();
inData = new int[wThr*h];
BufferedImage[] pieces = new BufferedImage[threads];
//instantiate array used for storing pieces of image
for (int i=0; i<threads; i++){
pieces[i] = new BufferedImage(wThr, h, BufferedImage.TYPE_BYTE_GRAY);
}
wThr = pieces[0].getWidth();
h = pieces[0].getHeight();
//instantiate target image
combined = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
//split into threads, each one taking a division of the image and running algorithm
Thread[] threadList = new Thread[threads];
for (int i = 0; i < threadList.length; i++) {
image.getRaster().getPixels((i*wThr), 0, wThr, h, inData);
threadList[i] = new Pr1();
threadList[i].start();
try{
threadList[i].join();
}catch (InterruptedException ie) {}
//Write images to pieces and draw pieces individually onto target image
pieces[i].getRaster().setPixels(0, 0, wThr, h, outData);
Graphics2D g = combined.createGraphics();
g.drawImage(pieces[i], i*(wThr), 0, null);
g.dispose();
}
outFile = new File("1.bmp");
ImageIO.write(combined, "BMP", outFile);
}
catch(IOException e)
{
// Handle the exception here!
}
}
这是使用2个线程处理时的图像:http://i.imgur.com/n5gasAW.png?1
任何人都对如何修复此问题有任何见解?我已经改变了BufferedImages和数组的各种参数,但我仍然没有运气。