This post explains how to let a thread wait/sleep and how to interrupt a thread.
What about Stop, suspend, and resume?
In this post, I won't cover the stop, suspend en resume methods because they are deprecated, which means that they are no longer recommended for use and may not be supported in future versions of Java. Using deprecated methods can lead to problems and issues in your code, as they may not work as intended or may not work at all. Additionally, more up-to-date methods may be more efficient and effective than deprecated ones, so it is generally best to avoid them in favour of newer, better-supported alternatives. Therefore, to ensure that the information and guidance provided to you are current and relevant.
You can use the interrupted() method from the Thread class to interrupt a (running) thread. Calling this method sets the interrupt flag on the thread to true. You can use this flag inside your concurrent code to check if your thread has to stop.
If the thread you interrupt is sleeping using
Thread.sleep() or waiting (
yourThread.wait();), the thread immediately exits by throwing
In the following example, we have a main method that starts a thread and immediately interrupts the thread's sleep method call. The example code catches and throws a new runtime exception to the caller.
Catching the interruption
Catching and not throwing the exception will cause the thread to continue. It will not stop when the thread is interrupted. To immediately exit the thread, you would have to throw to exception again and not let the code swallow it.
In this post, We looked at how to interrupt a thread and if you swallow the exception inside a try-catch, the thread will continue to run.