Java 中 Thread.sleep() 方法有什么用?


sleep() 方法是 Thread 类的静态方法,它使线程休眠/停止工作一段时间。如果线程被其他线程中断,则 sleep() 方法会引发 InterruptedException,这意味着 Thread.sleep() 方法必须用 try 和 catch 块括起来,或者必须用 throws 子句指定。

每当我们调用 Thread.sleep() 方法时,它都可以与线程调度器进行交互,以将当前线程置于等待状态一段时间。等待时间结束后,线程从等待状态变为运行状态。

语法

public static void sleep(long milliseconds)
public static void sleep(long milliseconds, int nanoseconds)

sleep(long milliseconds) 方法使线程仅休眠一段时间(以毫秒为单位)。

sleep(long milliseconds, int nanoseconds) 方法使线程休眠一段时间(以毫秒为单位)加上一段时间(以纳秒为单位)。

示例

class UserThread extends Thread {
   public void run() {
      for(int i=1; i <= 5; i++) {
         System.out.println("User Thread");
         try {
            Thread.sleep(1000); // sleep/stop a thread for 1 second
         } catch(InterruptedException e) {
            System.out.println("An Excetion occured: " + e);
         }
      }
   }
}
public class SleepMethodTest {
   public static void main(String args[]) {
      UserThread ut = new UserThread();
      ut.start(); // to start a thread
   }
}

输出

User Thread
User Thread
User Thread
User Thread
User Thread

更新日期:27-11-2023

5K+ 浏览

开启你的职业生涯

完成课程,获得认证

马上开始
广告
© . All rights reserved.