Java

How do you pause and resume threads in Java Programming3 min read

Based on the requirements sometimes you might want to suspend, resume or stop a thread. For doing such operations on a thread, before Java 2, thread API used to contain suspend(), resume() and stop() methods.

But all these methods might lead to undesired behavior of the program or machine. For example, these methods might lead to deadlock when a thread locked and is accessing a data structure and suddenly it is suspended or stopped. All other threads will be waiting indefinitely for gaining access to the data structure.




Because of this drawback of suspend(), resume() and stop() methods, they have been deprecated (should not be used) from Java 2 on wards.

Instead we have to check whether the thread is suspended or not through code itself. We can do that using a boolean variable which acts like a flag (ON / OFF).

Below program demonstrates the use of the boolean variable suspendFlag which is initially false. We write two more methods mySuspend() and myResume() which changes the value of the variable suspendFlag.

We have also used two more methods wait() and notify() from Object class. The wait() method suspends the current thread and the notify() method resumes (wakes up) the execution of the current thread.

Output of the above program is:

Child thread: Thread[First Thread,5,main]
Child thread: Thread[Second Thread,5,main]
Main thread is waiting…
First Thread: 1
Second Thread: 1
First Thread: 2
Second Thread: 2
—Suspending thread 1—
First Thread: 3
Second Thread: 3
Second Thread: 4
—Resuming thread 1—
First Thread: 4
Second Thread: 5
First Thread: 5
Second Thread is terminated
First Thread is terminated
Main thread terminated

In the above output you can observer that first thread is suspended for some time and has been resumed again.

Below program demonstrates stopping a thread:

Output of the above program is:

Child thread running!
Child thread running!
Child thread running!
Child thread running!
Child thread running!
Child thread stopped!

Take your time to comment on this article.

Leave a Comment