I’ve found the following code does not work because the while loop steals the lock indefinitely:
public void run()
{
while(true)
{
synchronized(run)
{
if (!run) break;
[code]
}
}
}
public void stopRunning()
{
synchronized(run)
{
run = false;
}
}
My goal is to ensure that I don’t return from a stopRunning() command until I know that my run() function is no longer actually running. I’m trying to prevent the run function from continuing to reference other things that I’m in the process of destroying. My first thought then is to add a line of code such as Thread.sleep(100) prior to synchronized(run) in order to ensure that it releases the lock. Is this the recommended practice or am I overlooking something [stupid/obvious]?
Thanks!
If you just need stopRunning() to block until run() finishes doing stuff, you could just use a CountDownLatch set to 1. Call it stoppedSignal or something, and in run() you can call stoppedSignal.countDown() when it is finished. In stopRunning you can then set your condition for run() to finish and then call stoppedSignal.await(). It won’t proceed until run() “releases” the latch by counting down. This is just one way to do it that would be a bit neater. All the synchronized block stuff that be got rid of.
Beware of the “synchronized” keyword – it’s a very blunt and old tool. There are some wonderful things in the concurrency package that fulfil specific purposes much more neatly. “Concurrency In Practice” is a fantastic book on it.