In a multi-threaded program, a task in a new thread, may be required to be stopped. This may be for many reasons, such as: (a) The result from the task is no longer required or (b) outcome from the task has gone astray or (c) The application is shutting down.
A thread can be stopped using a threading.Event object. An Event object manages the state of an internal flag that can be either set or not set.
When a new Event object is created, its flag is not set (false) to start. If its set() method is called by one thread, its flag value can be checked in another thread. If found to be true, you can terminate its activity.
Example
In this example, we have a MyThread class. Its object starts executing the run() method. The main thread sleeps for a certain period and then sets an event. Till the event is detected, loop in the run() method continues. As soon as the event is detected, the loop terminates.
When you execute this code, it will produce the following output −
Child thread running... 1 Child thread running... 2 Child thread running... 3 Child thread running... 4 Child thread running... 5 Child thread running... 6 Main thread stopping child thread Child Thread Interrupted
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.