Hi.
I have 2 threads in my application.
One of them is drawing the GUI at 30 frames per second.
The other frame is doing calculations.
The GUI thread should show the results of the calculating thread.
To keep the GUI thread up to date I thought about building a queue in which the calculation thread is putting commands which the GUI thread has to execute.
For this queue I have build a class which looks like this:
public class CommunicationPipeline { private static final Object lock = new Object(); private static LinkedList<Command> commands = new LinkedList<>(); private CommunicationPipeline(){} public static void add(Command command) { synchronized(lock) { commands.add(command); } } public static LinkedList<Command> get() { synchronized(lock) { LinkedList<Command> outgoingCommands = commands; commands = new LinkedList<>(); return outgoingCommands; } } }
And this is an example how these threads might communicate:
public class CalculationThread extends Thread { private boolean is_running; public void run() { while (is_running) { // do calculations CommunicationPipeline.add(new SomeCommand(...)); } } }public class GUIThread extends Thread { private boolean is_running; public void run() { while (is_running) { LinkedList<Command> commands = CommunicationPipeline.get(); for (Command cmd : commands) { cmd.execute(); } // render everything with set frame rate } } }
My question is, do I do this correctly? Is this a safe way to have 2 threads communicate with each other?
Thanks in advance.