import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.regex.Pattern; import javax.imageio.ImageIO; public class Fractal { public static int n; public static BufferedImage fractal; public static Pattern p; public static int threadNumber; private static int returnedThreads = 0; private static long t = System.nanoTime(); public static int[] rgbArray; public static void main(String[] args) throws IOException { n = Integer.parseInt(args[0]); p = Pattern.compile(args[1]); threadNumber = Integer.parseInt(args[2]); rgbArray = new int[n * n]; int section = (n * n) / threadNumber; for (int i = 0; i < threadNumber; i++) { Thread thread = new Thread(new FractalThread(n, section * i, section * (i + 1))); thread.start(); } fractal = new BufferedImage(n, n, BufferedImage.TYPE_INT_RGB); } public static synchronized void writeImage() throws IOException { returnedThreads++; if(returnedThreads >= threadNumber) { fractal.setRGB(0, 0, n, n, rgbArray, 0, n); File f = new File("fractal.png"); ImageIO.write(fractal, "PNG", f); System.out.println("Done in " + (System.nanoTime()-t)/1000000000F + " s"); } } } import java.io.IOException; import java.util.regex.Matcher; public class FractalThread implements Runnable { private int n; private int startingPoint; private int endPoint; public FractalThread(int n, int startingPoint, int endPoint) { this.n = n; this.startingPoint = startingPoint; this.endPoint = endPoint; } @Override public void run() { int[] privatePixels = new int[endPoint - startingPoint]; int index = 0; for (int i = startingPoint; i < endPoint; i++) { String code = getCode(i); Matcher m = Fractal.p.matcher(code); float percentage; int rgb = 0; if (m.find()) { String match = m.group(1); percentage = match.length()/(float)code.length(); } else { percentage = 1; rgb += (255 << 16) + (255 << 8); } int blue = (int) (255 * percentage); rgb += blue; privatePixels[index++] = rgb; if(i % 100000 == 0) System.gc(); } System.arraycopy(privatePixels, 0, Fractal.rgbArray, startingPoint, endPoint - startingPoint); try { Fractal.writeImage(); } catch (IOException e) { e.printStackTrace(); } } public String getCode(int pixel) { StringBuilder code = new StringBuilder(); int currentN = n; int x = pixel % currentN; int y = pixel / currentN; while (currentN > 1) { if (y >= currentN >> 1) { if (x >= currentN >> 1) { code.append("4"); x -= currentN >> 1; y -= currentN >> 1; } else { code.append("3"); y -= currentN >> 1; } } else { if (x >= currentN >> 1) { code.append("1"); x -= currentN >> 1; } else { code.append("2"); } } currentN = currentN >> 1; } return code.toString(); } }