Java 为什么不在第一次接球时就停止睡觉呢? publicstaticvoidmain(字符串s[]) { Thread t=Thread.currentThread(); t、 设置名称(“主”); 尝试 { 对于(int i=0;i

Java 为什么不在第一次接球时就停止睡觉呢? publicstaticvoidmain(字符串s[]) { Thread t=Thread.currentThread(); t、 设置名称(“主”); 尝试 { 对于(int i=0;i,java,interrupted-exception,interruption,Java,Interrupted Exception,Interruption,为什么它一直在运行 除非您告诉它,否则程序不会终止。它通常会继续运行。触发异常不会改变这一点。仅调用线程。睡眠不会触发中断异常。要使此代码引发中断异常,必须在线程上调用中断。将代码更改为 public static void main(String s[]) { Thread t=Thread.currentThread(); t.setName("main"); try { for(int i=0;i<=5;i++) {

为什么它一直在运行


除非您告诉它,否则程序不会终止。它通常会继续运行。触发异常不会改变这一点。

仅调用线程。睡眠不会触发中断异常。要使此代码引发中断异常,必须在线程上调用中断。将代码更改为

public static void main(String s[])
{
    Thread t=Thread.currentThread();
    t.setName("main");
    try
    {
        for(int i=0;i<=5;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);//interrupted exception(System provides error on its own) 
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("main thread interrupted");
    }
}

这里发生的事情是调用中断设置线程上的中断标志。当thread.sleep执行时,它会看到中断标志被设置,并基于此抛出InterruptedException。

那么……您是否触发了一个异常,导致
睡眠
终止?如果您不告诉我,为什么您会认为它会终止不想?
public class MainInterruptingItself {

    public static void main(String s[]) {
        Thread.currentThread().interrupt();
        try {
            for(int i=0;i<=5;i++) {
                System.out.println(i);
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException e) {
                System.out.println("main thread interrupted");
        }
    }
}
0
main thread interrupted