Thanks for replying,
sorry I should have been more clear.
the reason I want to stop the other thread is because the main thread is running a GUI so I'd rather kill the other thread before I dispose the GUI.
You may note that stop() is deprecated so I cannot (or at least should not) use that. Hence why I call join.
The class which implements Runnable has a stopRunning() method which sets a boolean to false. In run, there is a while loop using this variable which checks this. Problem is, the Runnable sleeps in that loop and I want to stop the Runnable straight away, not after the sleep.
here is a snippet
// fileListener is an instance of the class implementing Runnable.
pulbic void windowClosing(WindowEvent we)
{
fileListener.stopRunning();
if (fileListener.isAlive())
{
try
{
fileListener.join();
}
catch(InterruptedException ie)
{
System.out.println("Error");
}
}
dispose(); // the jframe
}
The run method
public void run()
{
while (keepRunning)
{
if (canDo)
do();
else
sleep(10000);
}
}
the stopRunning() method
public void stopRunning()
{
keepRunning= false;
}
does this clarify things?
Thanks,
John
Also be very careful doing a join() in the event thread here as you block the event threads ability to respond to any other events. As you are closing down it might not matter but a better solution would have the event thread call stopThread() (which sets the keepRunning flag - which better be volatile! - and calls interrupt() to break out of the sleep) and then have your filelistener thread post an "I'm done" event to the GUI
Of course if you filelistener doesn't touch the GUI then you don't need to wait for it to finish at all.
You might want to look at using a SwingWorker for your filelistener.
To expand on ejp's post ...
Object.wait()/notify()/notifyAll() are used together with monitor locks to communicate changes of state across threads. The thread waiting for the state change does:
synchronized(lock) {// lock is whatever object guards the state variable being tested
while (!inRightState) {
lock.wait();// you'll need to handle interrupts depending on how the blocking nature
// of this method is exposed to the caller
}
// do what needed to be done while in right state
}
While the state modifying thread does:
synchronized(lock) {
// change state and set flag
inRightState=true;
lock.notifyAll();// or notify() under right circumstances
}
In contrast suspend/resume can not be used to reliably communicate state changes across threads. The only form of suspend that is remotely safe is self-suspension, but even then reliable resume() is effectively impossible. Bottom line: forget suspend/resume exist as they can not be be used in any reliable way within an application.
Please check out a good text on concurrent programming in Java to find out more about this.