为什么我必须在try/catch语句中包装每个Thread.sleep()调用?

Ser*_*esh 2 java interrupted-exception interruption

我正在尝试用Java编写我的第一个多线程程序.我无法理解为什么我们需要围绕for循环进行此异常处理.当我在没有try/catch子句的情况下编译时,它会产生InterruptedException.(这是消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type InterruptedException
Run Code Online (Sandbox Code Playgroud)

)

但是当使用try/catch运行时,catch块中的sysout永远不会显示 - 这意味着没有捕获到这样的异常!

public class SecondThread implements Runnable{
    Thread t;

    SecondThread(){
        t = new Thread(this, "Thread 2");
        t.start();
    }

    public void run(){
        try{
            for(int i=5 ; i>0 ; i--){
                System.out.println("thread 2: " + i);
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException e){
            System.out.println("thread 2 interrupted");
        }
    }
}


public class MainThread{

    public static void main(String[] args){
        new SecondThread();

        try{
            for(int i=5 ; i>0 ; i--){
                System.out.println("main thread: " + i);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException e){
            System.out.println("main thread interrupted");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 5

Thread.sleep方法抛出InterruptedException,如果它检测到当前线程设置了中断标志,提前从睡眠状态唤醒并允许您使用异常将控制重定位到当前流之外的某个位置.只有在线程上调用中断时才会设置该标志.

由于您的程序不会在任何线程上调用中断,因此运行此程序时不会抛出InterruptedException.编译器仍然要求您捕获异常,因为它是在sleep方法上声明的已检查异常.

如果你将这样的方法添加到SecondThread

public void cancel() {
    t.interrupt();
}
Run Code Online (Sandbox Code Playgroud)

然后在main方法中调用cancel,如下所示:

public static void main(String[] args){
    SecondThread secondThread =  new SecondThread();

    try{
        for(int i=5 ; i>0 ; i--){
            System.out.println("main thread: " + i);
            Thread.sleep(2000);
            secondThread.cancel();
        }
    }
    catch(InterruptedException e){
        System.out.println("main thread interrupted");
    }
}
Run Code Online (Sandbox Code Playgroud)

你会看到在SecondThread的run方法中捕获InterruptedException的println.

在"问题"选项卡下的eclipse中会出现编译错误,除了通过红色下划线在编辑器中调出外,它们会在您编辑代码时显示出来.运行此程序时,任何异常都将与程序输出一起写入控制台.