Java中的Thread.sleep()– Java线程睡眠

本文详细介绍了Java中Thread.sleep()方法的使用,包括其基本语法、重载方法以及线程在睡眠过程中的行为特点。文章通过示例展示了如何在主线程中使用Thread.sleep()暂停执行,并解释了实际睡眠时间和指定时间可能存在的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java中的Thread.sleep (Thread.sleep in Java)

Thread.sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

Thread.sleep()方法可用于在指定时间(毫秒)内暂停当前线程的执行。 以毫秒为单位的参数值不能为负,否则会抛出IllegalArgumentException

There is another overloaded method sleep(long millis, int nanos) that can be used to pause the execution of current thread for specified milliseconds and nanoseconds. The allowed nano second value is between 0 and 999999.

还有另一种重载方法sleep(long millis, int nanos) ,可用于将当前线程的执行暂停指定的毫秒和纳秒。 允许的纳秒值在0到999999之间。

Java线程睡眠示例 (Java Thread Sleep Example)

Here is a simple program where Thread.sleep() is used to pause the main thread execution for 2 seconds.

这是一个简单的程序,其中Thread.sleep()用于将主线程执行暂停2秒钟。

ThreadSleep.java

ThreadSleep.java

package com.journaldev.threads;

public class ThreadSleep {

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(2000);
        System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start));
        
    }

}

If you will run the above program, you will notice that the thread sleep time it prints is slightly greater than 2000. This is caused by how thread sleep works and operating system specific implementation of thread scheduler.

如果您将运行上述程序,则会注意到它打印的线程睡眠时间略大于2000。这是由于线程睡眠的工作方式以及特定于操作系统的线程调度程序的实现所致。

Java线程睡眠要点 (Java Thread Sleep important points)

  1. It always pause the current thread execution.

    它总是暂停当前线程的执行。
  2. The actual time thread sleeps before waking up and start execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system it will be little bit more.

    线程在唤醒和开始执行之前Hibernate的实际时间取决于系统计时器和调度程序。 对于安静的系统,实际的睡眠时间接近于指定的睡眠时间,但是对于繁忙的系统,实际时间会更多。
  3. Thread sleep doesn’t lose any monitors or locks current thread has acquired.

    线程Hibernate不会丢失任何监视器,也不会锁定当前已获取的线程。
  4. Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

    任何其他线程都可以在睡眠中中断当前线程,在这种情况下会抛出InterruptedException。

线程睡眠如何工作 (How Thread Sleep Works)

Thread.sleep() interacts with the thread scheduler to put the current thread in wait state for specified period of time. Once the wait time is over, thread state is changed to runnable state and wait for the CPU for further execution. So the actual time that current thread sleep depends on the thread scheduler that is part of operating system.

Thread.sleep()与线程调度程序进行交互,以在指定的时间段内将当前线程置于等待状态。 等待时间结束后,线程状态将更改为可运行状态,并等待CPU进一步执行。 因此,当前线程睡眠的实际时间取决于操作系统中的线程调度程序。

翻译自: https://www.journaldev.com/1020/thread-sleep-java

### Java中`Thread.sleep(2500)`的具体含义 在Java中,`Thread.sleep(long millis)` 方法用于让当前正在执行的线程暂停指定的时间(以毫秒为单位),并进入休眠状态,在这段时间内不会消耗CPU资源[^3]。 对于 `Thread.sleep(2500)`,它的具体含义是: - 当前线程将会被挂起 **2500毫秒**,即 **2.5秒**[^3]。 - 时间单位是以毫秒计,因此参数值表示的是毫秒数而非秒数。 以下是该方法的一个简单示例代码: ```java public class SleepExample { public static void main(String[] args) { System.out.println("开始时间:" + new java.util.Date()); try { Thread.sleep(2500); // 让线程睡眠2500毫秒(2.5秒) } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("结束时间:" + new java.util.Date()); } } ``` 在这个例子中,程序会在控制台打印两次日期时间戳。第一次是在调用 `Thread.sleep()` 之前,第二次则是在线程完成休眠之后。两者之间的时间差大约为2500毫秒。 需要注意的是,尽管我们指定了具体的休眠时间,但由于操作系统调度机制的影响以及硬件精度限制等因素,实际的休眠时间可能会稍微超出设定值[^2]。 ### 关于误差的可能性 如果需要精确测量 `Thread.sleep(2500)` 是否严格遵循了2500毫秒的延迟,可以通过如下方式测试其准确性: ```java public class SleepAccuracyTest { public static void main(String[] args) { long startTime = System.nanoTime(); // 使用更精准的时间获取函数 try { Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.nanoTime(); double actualSleepTimeMs = (endTime - startTime) / 1_000_000.0; // 将纳秒转换为毫秒 System.out.printf("实际休眠时间为 %.2f 毫秒%n", actualSleepTimeMs); } } ``` 通过这种方式可以观察到由于系统调度等原因造成的微小偏差[^4]。 #### 注意事项 - 如果传入负数值作为参数,例如 `Thread.sleep(-1)`,会抛出非法参数异常 (`IllegalArgumentException`)。 - 若线程在休眠期间被捕获中断信号,则会抛出 `InterruptedException` 异常,并提前终止休眠过程[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值