Notice: Undefined index: sg in /usr3/euler/plotter/index.php on line 26
Java Plotter

parallelDemo

Zählen der Teiler von grossen Zahlen - einmal sequentiell und einmal parallel.

Bild

Code


package demos;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.stream.Stream;

import javax.swing.JButton;

import plotter.Graphic;
import plotter.LineStyle;
import plotter.Plotter;
import plotter.Point;

// Beispiel fuer Streams
// SE Juni 2021

public class FuncDemoDiv {
	Graphic graphic = new Graphic("Parallel Demo");
	Plotter plotter = graphic.getPlotter();
	double max = 100;
	List values = new ArrayList<>();
	String[] modes = { "Sequentiell", "Parallel" };

	Consumer plotConsumer = new Consumer() {
		public void accept(Point p) {
			plotter.add(p.getX(), countDivisors((int) p.getY()));
			plotter.repaint();
		}
	};

	public static void main(String[] args) {
		(new FuncDemoDiv()).demo();
	}

	private void demo() {
		fill();
		setUpPlotter();
		addButtons();
	}

	private void setUpPlotter() {
		plotter.setPreferredSize(new Dimension(700, 300));
		plotter.setDataLineStyle(LineStyle.HISTOGRAM);
		plotter.setHalfBarWidth(0.2);
		plotter.setXrange(0, max);
		plotter.setYrange(0, 150);
		plotter.setAutoYgrid(50);
		plotter.setStatusLine("Prozessoren: " + Runtime.getRuntime().availableProcessors());
		graphic.pack();
		graphic.revalidate();

	}

	private void addButtons() {
		for (String mode : modes) {
			JButton button = new JButton(mode);
			button.addActionListener(e -> doWork(mode));
			graphic.addSouthComponent(button);
		}
	}

	private void fill() {
		Random random = new Random();
		for (double x = 0; x < max; x += 1) {
			values.add(new Point(x, random.nextInt(100000000)));
		}
	}

	// zaehle die Anzahl der Teiler in einer gegegebenen Zahl
	// mit Absicht langsame Implementierung
	private int countDivisors(int number) {
		int count = 0;
		for (int divisor = 2; divisor < number; divisor++) {
			count += (number % divisor == 0) ? 1 : 0;
		}
		return count;
	}

	private void doWork(String mode) {
		new Thread() {
			public void run() {
				long t1 = System.currentTimeMillis();
				plotter.removeAllDataObjects();
				Stream stream = null;
				if (mode.equals("Parallel")) {
					stream = values.parallelStream();
				} else {
					stream = values.stream();
				}
				stream.forEach(plotConsumer);
				long t2 = System.currentTimeMillis();
				plotter.setStatusLine(mode + " Dauer: " + (t2 - t1) + " ms");
				graphic.repaint();
			}
		}.start();
	}
}