Многопоточность Java
Я пытаюсь реализовать многопоточность в моем приложении Java Mandelbrot:
Это то, что я до сих пор:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class MandelbrotSet {
private int numberOfIterations;
private double realMin;
private double realMax;
private double imaginaryMin;
private double imaginaryMax;
private int width;
private int height;
public BufferedImage image;
public Graphics2D imageGraphics;
public MandelbrotSet() {
// Set the width and the height
this.width = 600;
this.height = 400;
image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
imageGraphics = image.createGraphics();
this.realMin = -2.0;
this.realMax = 1;
this.imaginaryMin = -1;
this.imaginaryMax = 1;
this.numberOfIterations = 1000;
}
public Complex calculateComplexNumber(int x, int y) {
double realPart = realMin + x * (realMax - realMin) / (this.getWidth() - 1);
double imaginaryPart = imaginaryMax - y * (imaginaryMax - imaginaryMin) / (this.getHeight() - 1);
return new Complex(realPart, imaginaryPart);
}
public void calculateMandelbrotImagePoints() {
Thread[] threads = new Thread[4];
for (int i = 0; i < maxThreads; i++) {
threads[i] = new Thread(new MThread(i));
threads[i].start();
}
}
class MThread implements Runnable {
private int i;
public MThread(int i) {
this.i = i;
}
//Method uses the thread number to draw the mandelbrot in columns
public void run() {
for (int x = i; x < width; x += 4) {
for (int y = 0; y < height; y++) {
int n = 0;
Complex c = calculateComplexNumber(x, y);
Complex z = c;
while ((zNumber.modulusSquared() < 4.0D) && (n < numberOfIterations)) {
z = z.square();
z.add(c);
n++;
}
if (n == numberOfIterations) {
imageGraphics.setColor(Color.BLACK);
} else {
imageGraphics.setColor(Color.getHSBColor(n / 100.0F, 1, 1));
}
imageGraphics.drawLine(x,y,x,y);
}
}
}
}
}
Проблема, которая возникает, заключается в том, что при рисовании изображения отображаются неправильные пиксели:
Когда я проверяю поток с чем-то вроде:
threads[i].isAlive();
изображение, кажется, отображается успешно, однако изображение занимает гораздо больше времени (до 3 раз) для рендеринга.
Мне было интересно две вещи.
Куда я иду не так?
Что было бы лучшим способом для рисования Мандельбротов вBufferedImage
для большого количества итераций (> 1000)?