Java TimeUnit sleep()方法及示例

来源:这里教程网 时间:2026-02-17 21:15:05 作者:

Java TimeUnit sleep()方法及示例

TimeUnit类的sleep()方法用于使用该时间单位执行Thread.sleep。这是一个方便的方法,可以将时间参数睡成Thread.sleep方法所要求的形式。

语法。

public void sleep(long timeout)           throws InterruptedException

参数。该方法接受一个强制性参数timeout,它是睡眠的最小时间。如果这个参数小于或等于0,那么就根本不进行睡眠。

返回值。这个方法不返回任何东西。

异常。如果在睡眠时被打断,该方法会抛出InterruptedException。

下面的程序说明了TimeUnit sleep()方法的实现。

程序 1:

// Java program to demonstrate// sleep() method of TimeUnit Class  import java.util.concurrent.*;  class GFG {    public static void main(String args[])    {        // Get time to sleep        long timeToSleep = 0L;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          try {              System.out.println("Going to sleep for "                               + timeToSleep                               + " seconds");              // using sleep() method            time.sleep(timeToSleep);              System.out.println("Slept for "                               + timeToSleep                               + " seconds");        }          catch (InterruptedException e) {            System.out.println("Interrupted "                               + "while Sleeping");        }    }}

输出:

Going to sleep for 0 secondsSlept for 0 seconds

程序2。

// Java program to demonstrate// sleep() method of TimeUnit Class  import java.util.concurrent.*;  class GFG {    public static void main(String args[])    {        // Get time to sleep        long timeToSleep = 10L;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          try {              System.out.println("Going to sleep for "                               + timeToSleep                               + " seconds");              // using sleep() method            time.sleep(timeToSleep);              System.out.println("Slept for "                               + timeToSleep                               + " seconds");        }          catch (InterruptedException e) {            System.out.println("Interrupted "                               + "while Sleeping");        }    }}

输出:

Going to sleep for 10 secondsSlept for 10 seconds

相关推荐