gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:39:50 26 4
gpt4 key购买 nike

要编译这段代码,我可以:

为什么我必须这样做?

class Test {
public static void main( String[] args ) {
printAll( args );
}

public static void printAll( String[] line ) {
System.out.println( lines[ i ] );
Thread.currentThread().sleep( 1000 ):
}
}

(来自 Kathy Sierra's SCJP book 的示例代码。)

我知道Thread.sleep()抛出的异常是checked exception,所以我要处理,但是Thread.sleep()在什么情况下> 需要抛出这个异常吗?

最佳答案

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

Thread.sleep()声明如下:

public static void sleep(long millis) throws InterruptedException;

它可能会抛出 InterruptedException直接扩展java.lang.Exception所以你必须捕获它或宣布扔掉它。

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

示例:

Thread t = new Thread() {
@Override
public void run() {
try {
System.out.println("Sleeping...");
Thread.sleep(10000);
System.out.println("Done sleeping, no interrupt.");
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
e.printStackTrace();
}
}
};
t.start(); // Start another thread: t
t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call
// inside t's run() method will throw an InterruptedException!

输出:

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

关于java - 为什么我需要处理 Thread.sleep() 的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26703324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com