Java Thread.sleep():设置线程休眠(附带实例)
线程休眠是我们经常使用的操作,特别是在开发环境中调试的时候,有时为了模拟长时间的执行就会通过休眠。该操作对应 java.lang.Thread 类的 sleep() 方法,它能使当前线程休眠指定的时间。
Thread 类的 sleep() 方法需要传入一个整数参数,表示休眠的时长,单位是毫秒。
下面通过一个简单的例子来看 sleep() 方法的操作:
该方法只针对当前线程,即让当前线程进入休眠状态,哪个线程调用 Thread.sleep() 则哪个线程休眠。
从上面示例中可以看到调用 sleep() 方法时需要处理 InterruptedException 异常,它提供了一种提前结束休眠的机制。
下面的实例展示了 InterruptedException 异常的作用:
Thread 类的 sleep() 方法需要传入一个整数参数,表示休眠的时长,单位是毫秒。
下面通过一个简单的例子来看 sleep() 方法的操作:
public class ThreadSleepTest {
public static void main(String[] args) {
System.out.println("当前线程休眠3000ms");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休眠结束");
}
}
程序中,我们让主线程休眠 3000ms。主线程先输出“当前线程休眠3000ms”,然后暂停 3s,最后输出“休眠结束”。该方法只针对当前线程,即让当前线程进入休眠状态,哪个线程调用 Thread.sleep() 则哪个线程休眠。
从上面示例中可以看到调用 sleep() 方法时需要处理 InterruptedException 异常,它提供了一种提前结束休眠的机制。
下面的实例展示了 InterruptedException 异常的作用:
public class ThreadSleepTest {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("thread1 sleeps for seconds.");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
System.out.println("thread1 is interrupted by thread2.");
}
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 interrupts thread1.");
thread1.interrupt();
});
thread1.start();
Thread.sleep(2000);
thread2.start();
}
}
输出结果:
thread1 sleeps for 30 seconds.
thread2 interrupts thread1.
thread1 is interrupted by thread2.
ICP备案:
公安联网备案: