Interrupting a thread from inside a runnable class? (java)
I am trying to set up a method inside a class that implements the runnable interface that will set the interrupt status of that class. The reason i want to be able to do it from inside the class is there is some other clean up stuff that i need to take care of as well, and i would like to be able to do it all by calling one method instead of calling, for example:
Gui gui = new Gui() // class that implements runnable
Thread guiThread = new Thread(gui, "gui thread");
guiThread.start()
...
...
guiThread.interrupt();
gui.cancel();
Currently my cancel code looks like this, however it isn't correctly setting the interrupt status of this thread.
public void cancel()
{
Thread.currentThread().interrupt();
// other clean up code here.
}
Any advice on if/how i could get this working?
Thanks.
EDIT: I wh开发者_Go百科en i tried to get the cancel working, i commented out the guiThread.interrupt(), so that i wasn't just setting the status the reseting the status.
You want to simply call interrupt() - this will interrupt the guiThread, and not the calling thread. E.g.
public void cancel()
{
guiThread.interrupt();
// other clean up code here.
}
However, are you sure you want the cleanup code running on the calling thread? It is usually best to have the thread itself do its own cleanup. You don't know when the thread is interrupted and ready to be cleaned up. You could add a join() after interrupt() if the thread will exit when interrupted, but this is generally less preferable to simply having the thread itself do the cleanup. (Later, you may not even have separate threads for these tasks, but use a thread pool. Putting cleanup in with the task will make this much easier to manage.)
Finally, please be aware that your thread doesn't automatically interrupt and stop what it's doing - you need to call methods that check the interrupt status, such as Object.wait(), Thread.sleep() etc. or you can explicitly check the interrupt status via Thread.isInterrupted().
EDIT: It thought cancel() was on the guiThread. It's not, so I've changed the interrupt call.
If you want to do everything inside of cancel
, just add a Thread
parameter to it and pass a guiThread to it.
void cancel ( final Thread guiThread )
{
guiThread.interrupt( );
guiThread.join( );
// other cleanup code
...
}
Caller code
Gui gui = new Gui() // class that implements runnable
Thread guiThread = new Thread(gui, "gui thread");
guiThread.start()
...
...
gui.cancel( guiThread );
guiThread.interrupt(); should work fine, but if you want to interrupt your thread from inner class method, you should do:
public void cancel() {
if (isAlive()) {
this.interrupt();
}
}
or
public void cancel() {
if (!isInterrupted()) {
interrupt();
}
}
精彩评论