How to solve the setColor() problem with multithreading?

My fractal program uses a custom number of threads to draw the complete image. If I use just 1 thread, the image looks clean, if I use more threads some pixels of the image gets other colors. The problem ist the painting code:

g2d.setColor(col);

g2d.drawLine(x, y, x, y);

as it is necessary to first set the color of the graphics object and then draw the line. I can solve this pixel color problem by synchronizing the Graphics2D object:

synchronized (g2d){

g2d.setColor(col);

g2d.drawLine(x, y, x, y);

}

but this slows the code down to times where just 1 thread is calculating the image. Unfortunately, I can't find a draw() method that has a color parameter.

I tried to divide the panel into multiple BufferedImages (1 for each thread) which solves the pixel problem but only the first BufferedImage get's drawn.

[965 byte] By [MartinHilperta] at [2007-10-3 7:25:51]
# 1

When you divide the panel into mulitple BufferedImages are you writing to an image with an alpha channel?If the images have alpha values you should be able to layer them. How are you making sure the fractal threads are done drawing to their bufferedimages before you draw the total image? A CountDownLatch?

twba at 2007-7-15 2:24:32 > top of Java-index,Security,Cryptography...
# 2

I solved my problem now. My solution is to use a separate BufferedImage for each Thread. I still had a bug where i didn't transformed the x/y coordinates of the complete image to the shifted x/y coordinates of the single BufferedImages, so that the threads draw the image out of the visible area which looked like all threads after the first only had a black image. After adjusting teh coordinates, the fractal now gets drawn correctly. And boy it's much faster with multiple threads - even on single core systems. On a dual core system, using 10-20 threads about doubles the performance as both cores have work almost all the time until the fractal is finished. :-)

MartinHilperta at 2007-7-15 2:24:32 > top of Java-index,Security,Cryptography...