java – 为什么需要处理Thread.sleep()的异常?

前端之家收集整理的这篇文章主要介绍了java – 为什么需要处理Thread.sleep()的异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
要得到这个代码进行编译,我可以:

>把我的电话号码Thread.sleep()放在try / catch块里,或者
> printAll()声明它可以抛出一个InterruptedException.

为什么要这样做?

  1. class Test {
  2. public static void main( String[] args ) {
  3. printAll( args );
  4. }
  5.  
  6. public static void printAll( String[] line ) {
  7. System.out.println( lines[ i ] );
  8. Thread.currentThread().sleep( 1000 ):
  9. }
  10. }

(Kathy Sierra’s SCJP book的示例代码)

我知道Thread.sleep()抛出的异常是一个被检查的异常,所以我必须处理它,但在什么情况下Thread.sleep()需要抛出这个异常?

解决方法

如果以一种方式声明方法可以抛出已检查的异常(异常不是RuntimeException的子类),调用它的代码必须在try-catch块中调用它,或者调用方法必须声明抛出它.

Thread.sleep()被宣布为:

  1. public static void sleep(long millis) throws InterruptedException;

它可能会抛出InterruptedException直接扩展java.lang.Exception,所以你必须抓住它或声明抛出它.

为什么Thread.sleep()以这种方式声明?因为如果Thread正在睡眠,线程可能被中断,例如与另一个线程Thread.interrupt(),在这种情况下,休眠线程(sleep()方法)将抛出此InterruptedException的实例.

例:

  1. Thread t = new Thread() {
  2. @Override
  3. public void run() {
  4. try {
  5. System.out.println("Sleeping...");
  6. Thread.sleep(10000);
  7. System.out.println("Done sleeping,no interrupt.");
  8. } catch (InterruptedException e) {
  9. System.out.println("I was interrupted!");
  10. e.printStackTrace();
  11. }
  12. }
  13. };
  14. t.start(); // Start another thread: t
  15. t.interrupt(); // Main thread interrupts t,so the Thread.sleep() call
  16. // inside t's run() method will throw an InterruptedException!

输出

  1. Sleeping...
  2. I was interrupted!
  3. java.lang.InterruptedException: sleep interrupted
  4. at java.lang.Thread.sleep(Native Method)
  5. at Main$1.run(Main.java:13)

猜你在找的Java相关文章