Reputation: 7145
I have created a class which extends Thread.
This class has several methods defined, some of which use Process and IO streams to download files (sometimes taking several minutes).
I also have a JButton which I use to stop the thread, it has an ActionListener which currently performs a ClassName.this.stop(); and this works perfectly.
Within the 'public void run()' method, I execute some of these methods and start the thread.
My question is, how can I replace my deprecated Thread.stop() method with an interrupt(), and use it to cleanly stop the thread?
I have looked at some solutions, which recommend using a boolean flag to check whether the thread has been interrupted, but seeing that the run() method simply executes a series of methods, the loop does not evaluate until all the methods have finished executing, and even then, I get a 'InterrupedException' and then the loop starts again.
Another issue is that if a download is in progress, it could take minutes for the download to complete and for the next check to see if the Thread has been interrupted. I'd like everything to stop and for the object to 'delete itself and everything in it', which is what Thread.stop() is currently doing correctly.
Any ideas anyone?
Upvotes: 0
Views: 121
Reputation: 200148
Don't use extra boolean sentinel flags, rely fully on the interruption mechanism. In long-runnig tasks which don't spend time in interruptible blocking methods; you must handcode occasional checks of Thread.interrupted()
and break out of the task if true
. If your loop goes on after InterruptedException
, then fix this behavior. This aspect is completely in your hands. Don't ignore the exception; react by curtailing the work and ending the method.
Upvotes: 2