在没有 try/catch 的情况下进行延迟,或者在一个函数中使用它

Hel*_*234 5 java delay

我想让我的简单小程序尽可能不杂乱。目前我所有的延迟都像

try
{
    TimeUnit.SECONDS.sleep(1);
}
catch(InterruptedException e)
{
}
Run Code Online (Sandbox Code Playgroud)

但它真的很杂乱。我想要某种功能,例如

try
{
    TimeUnit.SECONDS.sleep(Delay);
}
catch(InterruptedException e)
{
}
Run Code Online (Sandbox Code Playgroud)

然后让它以某种方式被这样调用

delay(3)
Run Code Online (Sandbox Code Playgroud)

或者,只是摆脱try/catch一般的声明。那可能吗?

Hov*_*els 3

只需创建一个吞掉 try/catch 的方法即可。

public void timeDelay(long t) {
    try {
        Thread.sleep(t);
    } catch (InterruptedException e) {}
}
Run Code Online (Sandbox Code Playgroud)

任何时候你想睡觉,都可以调用该方法。

public void myMethod() {
    someCodeHere();
    timeDelay(2000);
    moreCodeHere();
}
Run Code Online (Sandbox Code Playgroud)