如何在 Java 中使用 TimeUnit

Ibr*_*yan 4 java time exception java.util.concurrent

我正在尝试在 Java 中使用 TimeUnit,但它只是向我发送错误这就是我写的

import java.util.concurrent.TimeUnit ;

public class Anything { 
    public static void main( String[] args ) {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}
Run Code Online (Sandbox Code Playgroud)

Lal*_*rma 7

试试这个,因为你的代码有很多syntax errors以及你handling Exception在调用 期间没有的TimeUnit.SECONDS.sleep(6);,要么使用 throws 要么用 try catch 包围它。

import java.util.concurrent.TimeUnit ;

public class Anything { 
    public static void main( String[] args ) throws InterruptedException {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}
Run Code Online (Sandbox Code Playgroud)