javaconcurrency

Thread suspend technique with out using suspend API in java


I am reading about thread in Java book by Cay S Horstman. Below is text snippet.

If you want to safely suspend a thread, introduce a variable "suspendRequested" and test it in a safe place of your run method - in a place where your thread does not lock objects that other threads need. When your thread find that the "suspendRequested" variable has been set, it should keep waiting until it becomes available again.

My question is

Suppose threadA is running and it wants to be suspended it will check "suspendRequested" and if it is set it will wait, this this point it is clear. My question is who will set "suspendRequested" to true and how threadA will know it should start again? Kindly explain this


Solution

  • controllerThread sets the suspendRequested flag to true when it wants to pause threadA. threadA checks this flag if it's in run() method and, if it's set, it enters a waiting state using wait() or Thread.sleep(). To resume threadA, the controlling thread sets suspendRequested back to false and calls notify() to wake threadA up.