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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26703324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:06:47  来源:igfitidea点击:

Why do I need to handle an exception for Thread.sleep()?

javamultithreadingexception

提问by geeks

To get this code to compile, I can either:

要编译此代码,我可以:

Why do I have to do this?

为什么我必须这样做?

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 ):
    }
}

(Sample code from Kathy Sierra's SCJP book.)

(来自Kathy Sierra 的 SCJP 书籍的示例代码。)

I know that the exception which Thread.sleep()throws is a checked exception, so I have to handle it, but in what situation does Thread.sleep()need to throw this exception?

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

采纳答案by icza

If a method is declared in a way that it can throw checked exceptions (Exceptions that are not subclasses of RuntimeException), the code that calls it must call it in a try-catchblock or the caller method must declare to throw it.

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

Thread.sleep()is declared like this:

Thread.sleep()声明如下:

public static void sleep(long millis) throws InterruptedException;

It may throw InterruptedExceptionwhich directly extends java.lang.Exceptionso you have to catch it or declare to throw it.

它可能会抛出InterruptedException直接扩展的内容,java.lang.Exception因此您必须捕获它或声明抛出它。

And why is Thread.sleep()declared this way? Because if a Threadis sleeping, the thread may be interrupted e.g. with Thread.interrupt()by another thread in which case the sleeping thread (the sleep()method) will throw an instance of this InterruptedException.

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

Example:

例子:

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!

Output:

输出:

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

回答by chiastic-security

One Threadcan communicate with and interact with another Thread, and one way that it can do it is by interrupting it: if tis another Thread, you can call t.interrupt()to ask it politely to stop what it's currently doing. This is in particular something you might want to do if tis sleeping: you might want to wake it up. What it does is to cause an InterruptedExceptionin t's Thread.sleep()method, so that it can catch it and respond. Because of this, any time you use Thread.sleep()to make the current thread go to sleep, you have to deal with the possibility of an InterruptedExceptionin case another thread decides to wake it up.

一个人Thread可以与另一个人交流和互动Thread,一种方法是打断它:如果t是另一个人Thread,你可以t.interrupt()礼貌地打电话要求它停止当前正在做的事情。如果t您正在睡觉,这尤其是您可能想要做的事情:您可能想要唤醒它。它所做的是引发一个InterruptedExceptionintThread.sleep()方法,以便它可以捕获它并做出响应。正因为如此,任何时候你Thread.sleep()用来让当前线程进入睡眠状态,你都必须处理InterruptedException另一个线程决定唤醒它的可能性。

In your case, you've only got one Thread, so you know that there can't be an InterruptedExceptionfrom elsewhere in your code. But it's a not uncommon thing to want to do in multi-threaded code.

在您的情况下,您只有一个Thread,因此您知道InterruptedException代码中不能有来自其他地方的 。但是在多线程代码中想要做的事情并不少见。

回答by ziyad

 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();
            }}

Suppose We have two Thread t and t2 and t is executing while executing, t2 came and t2 is also start executing but t is not finish yet there the thread get interrupted and you lose your data.In above example t thread is running and when in spleeping mode, and there t2 came and start executing suddenly t get up but t2 is running this is chance of interruptedexception and data lose to avoid this we use interruptedexception

假设我们有两个线程 t 和 t2 并且 t 在执行时正在执行,t2 来了并且 t2 也开始执行但是 t 还没有完成,线程被中断并且你丢失了数据。在上面的例子中,t 线程正在运行,当在睡眠模式,t2 来了并突然开始执行 t 起床但 t2 正在运行这是中断异常和数据丢失的机会以避免这种情况我们使用中断异常