I have made a java program with GUI and have placed a "stop" button on it. When I start the program, the main thread starts 10 threads. Now I want that whenever a user click on "stop" button, all the threads should terminate first, then the main thread should terminate. How can I do that.
It depends on how you want to the 10 threads to "terminate", and how you are running the threads.
I recommend creating an ExecutorService
, and writing your "threads" as Runnable
implementations. These Runnable
objects should respond to calls to interrupt()
on their thread of execution by aborting their task, cleaning up, and exiting the run
method as quickly as possible.
Submit these Runnable
tasks to an ExecutorService
then call awaitTermination
, all in the main thread. When the user presses the "stop" button, call shutdown
or shutdownNow
as desired on the ExecutorService
(from the event dispatch thread).
If you call shutdownNow
on the executor service, it will notify the running tasks by interrupting their threads. If you call shutdown
, it will allow the tasks to complete without interruption. Regardless, your main thread will block on awaitTermination
until all of the tasks have completed (or the time limit runs out).
You can, of course, create and manage of all of the threads yourself, using join
. The key is to make the threads interruptible if you want to be able to stop them prematurely.
Firstly, let me note that there is a tempting method on the Thread
class called stop()
. Do not use it, it is dangerous.
One way of doing this is to code your 10 threads to check the interrupted status of the thread.
e.g.
while (! Thread.interrupted())
{
// Do your thread's work
}
You can interrupt each worker thread by calling the interrupt()
method on the Thread
object, and then calling join()
to wait for the thread to actually finish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With