为什么我需要处理Thread.sleep()的exception?
为了使这段代码能够编译,我可以:
- 把我对
Thread.sleep()
调用放在try / catch块中,或者 - 让
printAll()
声明它可以抛出InterruptedException
。
为什么我要这样做?
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的SCJP书 。)
我知道Thread.sleep()
抛出的exception是一个已检查的exception,所以我必须处理它,但Thread.sleep()
在什么情况下需要抛出此exception?
如果一个方法以一种可以抛出已检查exception的方式声明( Exception
s不是RuntimeException
子类),则调用它的代码必须在try-catch
块中调用它,否则调用方法必须声明抛出它。
Thread.sleep()
声明如下:
public static void sleep(long millis) throws InterruptedException;
它可能抛出InterruptedException
,它直接扩展java.lang.Exception
所以你必须捕获它或声明抛出它。
为什么Thread.sleep()
这种方式声明? 因为如果一个Thread
处于hibernate状态,线程可能会被中断,例如Thread.interrupt()
被另一个线程中断,在这种情况下,hibernate线程( 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)
一个Thread
可以与另一个Thread
通信并与之交互,并且它可以通过中断它来实现它的一种方式:如果t
是另一个Thread
,你可以调用t.interrupt()
来礼貌地要求它停止它当前正在做的事情。 如果你正在睡觉,这尤其是你可能想做的事情:你可能想把它唤醒。 它的作用是在t
的Thread.sleep()
方法中引起InterruptedException
,以便它可以捕获并响应。 因此,只要你使用Thread.sleep()
使当前线程进入hibernate状态,你就必须处理InterruptedException
的可能性,以防另一个线程决定将其唤醒。
在您的情况下,您只有一个Thread
,因此您知道代码中的其他地方不会出现InterruptedException
。 但是在multithreading代码中想要做的事情并不少见。
class Demo extends Thread{ public void run() { for (int i = 0; i <10; i++) { system.out.println("hello Ziyad"); thread.sleep(1000); }} } public class Threddemo{ public static void main(string[] args) throws interruptedexception { Demo t=new Demo(); Demo t2=new Demo(); t.start(); t2.start(); }}
假设我们有两个Thread t和t2并且t在执行时正在执行,t2来了,t2也开始执行但是t还没有完成,那里线程被中断并且你丢失了你的数据。在上面的例子中t线程正在运行并且在脾模式,然后有t2来了,突然开始执行但是t2正在运行这是中断值和数据丢失的机会,以避免这种情况我们使用interrupttedexception