Thread.sleep()

Thread.sleep()方法的异常处理有哪些方法

小樊
95
2024-08-14 04:07:36
栏目: 编程语言

  1. 使用try-catch块捕获InterruptedException异常,因为Thread.sleep()方法会抛出InterruptedException异常。

示例代码:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
  1. 在方法签名中声明抛出InterruptedException异常,将异常传递给调用方法处理。

示例代码:

public void sleep() throws InterruptedException {
    Thread.sleep(1000);
}
  1. 使用Thread.currentThread().interrupt()重新中断当前线程。

示例代码:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}
  1. 忽略InterruptedException异常,不对其进行处理。

示例代码:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // do nothing
}

0
看了该问题的人还看了