Search code examples
javamultithreadingsleep

Continue sleeping for remaining time when thread is interrupted


I have network requirement who forces me to idle request sending for 2 seconds

requester = new Thread(){
        @Override
        public void run(){
                  buildRequest();
                  Thread.sleep(requestDelay);
                } catch( InterruptedException e){
                   // keep idle for the remaining time still
                   // interrupted at 1s need to sleep 1 second more
                   e.printStackTrace();
                }
                sendRequest();
            }
        }

Is it possible to still sleep for remaining time with consuming CPU with a loop? If yes is the best way ?


Solution

  • If I understood correctly you want to handle the InterruptedException in such way to unsure a delay before executing sendRequest. Well, since the InterruptedException happens when something calls interrupt() on the thread, that catch block doesn't get executed so you don't have to worry about.

    Your approach is not quite right, a reactive approach would be better. Even a basic Timer is better.