Home > OS >  Why sometimes, in threads, do you have to put sleep in a loop in the run method?
Why sometimes, in threads, do you have to put sleep in a loop in the run method?

Time:06-12

Many times I have seen that in some sample solutions, if it said stop the thread every second, the creator did something like this, in the run method:

while(true){
    try{
       sleep(1000);
     }catch{...}
    //And following everything inside, what the run method should execute
}

So in a while loop that executes infinitely. Otherwise, I have also seen this:

//codethat should be executed

try{
    sleep(1000);
}catch{...}
//(Without while loop, only in try catch block)

Why sometimes they put the sleep method in a loop, and sometimes not?

In some solutions, where the creator of the code put sleep in a loop and then I removed the loop, the code stopped working. In other cases where it was not in a loop, and I put it in a loop, the code resulted in errors.... Why?

How can I know when I have to put it in a loop?

CodePudding user response:

In these sample codes, sleep is mainly used to demonstrate a simulation who threads are working parallelly. If sleep is not used, then we won't be able differentiate if the code running in main thread or other thread.

Also putting the sleep inside makes the thread wait for 1 sec and executes the code thereafter for infinite period. The thread will not terminate and run for infinite period doing the same thing at regular interval. But when loop is not used, the code is only ran once and the thread waits for 1 sec and terminates. So it is mainly about the other piece of code doing.

  • Related