I have two threads. One runs a simulation and one runs a UI.
In the UI, it is possible to trigger a "tick" of the simulation. There are a few constraints:
- Ticks run on the simulation thread
- Each tick takes a bit of time to complete.
- When the user asks for
n
ticks,n
ticks should be completed, even if they are requested during the execution of a tick.
To manage the triggering of ticks between threads, I have created a Pulse
class. Here it is:
public final class Pulse {
private final Object Lock = new Object();
private volatile int count;
public Pulse() {
super();
count = 0;
}
public void pulse() {
synchronized (Lock) {
count++;
Lock.notifyAll();
}
}
public void waitForPulse() throws InterruptedException {
synchronized (Lock) {
while (count == 0) {
Lock.wait();
}
count--;
}
}
}
A single Pulse
instance is shared between the UI and simulation threads.
In the UI thread I would have something like:
void onTickRequested() {
simulationPulse.pulse();
}
And in the simulation thread I have something like:
while (isRunningSimulation) {
myPulse.waitForPulse();
tick();
}
Will my code work as expected? Is it thread-safe?