My assignment is to add threading to a Java program that creates an "Orbital Fractal" through a GUI that allows the viewer to adjust colors, number of dots, etc. I've got the basic program all finished from a previous assignment, but I'm lost in regards to adding threading.
My basic confusion comes from the fact that almost every threading tutorial I've come across so far has the main class of the program using the threading. In the program we're doing, the main class runs everything, but only the drawing section of the application is supposed to be run in a thread.
In order to make this drawing be done in a thread should I be changing the main class of the application to be threaded and somehow include the above drawing code in a run function, or is there some way to convert the above function to be run as a thread?
Create a class that implements Runnable, place the method in that, and call it from the run method. Runnable will exit, when drawing is done. When ever user initiates a change, that would provoke calling the drawFractal method, use SwingUtils.invokeLater(...) to launch a new Thread (one of the runnables you created). Give it the right Graphics as param and you are home free.
So basically you are assuring that each custom paint call is done in AWT-EDT, and executed asynchronously, at the earliest inconvinience. Or if you want to accertain that only one drawing is done at a time (might make sense), use executors singleThreadPool, which will accept the runnable and launch when available. Place the SwingUtils check in the run method of the runnable.
As Londbrok implies, you should do GUI tasks (e.g. Swing painting) in the Swing 'Event Despatch Thread' (EDT). In Java 5, this means using SwingUtilities.invokeLater(Runnable), which will wait until all Swing events have finished before running the Runnable in the EDT.
In Java 6, you can use SwingWorker, which does the same kind of thing, but is easier and more flexible to use. With SwingWorker, you can either do a one-off background calculation and update the GUI when it finishes, or you can do continuous calculations in the background, and periodically update the GUI with the latest results.