I have a Runnable class that I’m writing. Inside of it, I have two methods. The run() method, and another method called stopRunning(). stopRunning() is to be called by a separate thread from the one that’s running the run() method and is to stop the thread running the run() method from running.
Here’s a code snippet:
public class myRunnable implements Runnable
{
private boolean stillRunning = true;
public void stopRunning()
{
synchronized (this)
{
stillRunning = false;
}
}
public void run()
{
while (stillRunning)
{
synchronized (this)
{
// do some stuff that doesn't involve the isPlaying var
}
}
}
}
Does this code look correct? Do I need to synchronize to ensure that the change of isPlaying will be recognized by the thread running the run() method?
Also, do I need to call notify() or notifyAll() anywhere here for this to work? I’m pretty sure I don’t since I never call wait(), but I’m not 100% sure.
EDIT: woops, my code was wrong. I used the wrong name for the boolean, sorry about that. It’s fixed now.
For the starting and stopping a thread, the Java Thread API already provides the functionality you are looking for.
Thread.interrupt()andThread.interrupted()can be used to achieve what you want.Whenever you want to interrupt
MyThreadjust callMyThread.interrupt()