线程中断时继续休眠剩余时间

Continue sleeping for remaining time when thread is interrupted

我有网络要求,迫使我空闲请求发送 2 秒

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();
            }
        }

是否可以在循环消耗 CPU 的情况下继续睡眠剩余时间?如果是,最好的方法是什么?

如果我理解正确的话,你想以这种方式处理 InterruptedException 以确保在执行 sendRequest 之前有延迟。好吧,由于 InterruptedException 在线程上调用 interrupt() 时发生,因此 catch 块不会执行,因此您不必担心。

你的方法不太对,反应式方法会更好。即使是基本的 Timer 也更好。