Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop threads of a Java program?

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.

like image 640
Yatendra Avatar asked Nov 28 '22 15:11

Yatendra


2 Answers

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.

like image 83
erickson Avatar answered Dec 16 '22 00:12

erickson


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.

like image 31
Simon Nickerson Avatar answered Dec 16 '22 02:12

Simon Nickerson