有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果在线程中InterruptedException的catch块中使用,“return”在哪里返回?

这对你们来说可能是一个非常简单的问题,但若你们能帮我澄清我对此的疑问,我将不胜感激

假设我创建了一个使用sleep()方法的线程,并从我的主方法中断它

这是我的代码片段

class myThread implements Runnable{
    volatile boolean checking=true;
    int counter =1;
    public void run()
    {
         while(checking)
         {
              System.out.println(Thread.currentThread().getName() + " - count - "+counter++);
              try{
                  Thread.sleep(1000);
              }catch(InterruptedException e){
                  System.out.println("Interrupted");
                  Thread.currentThread().interrupt();
                  return;  //line of confusion
              }

         }
    }
    public void stopCounting()
    {
        checking = false;
    }
    public boolean getCheker()
    {
        return checking ;
    }

}
//main class 
public class Demo{
    public static void main(string args[])
    {
        myThread th = new myThread();
        Thread t1 = new Thread(th);
        t1.start();
        for(int i=0;i<50000;i++)
        {
            //do nothing
            System.out.println("Do nothing...");
        }
        t1.interrupt();
        System.out.println("Press enter to stop the counter....");

        Scanner sc = new Scanner(System.in);
        sc.nextLine();
        th.stopCounting();

        //this line is executed when I am not using return statement
        // in thread
        System.out.println("value of while loop cheker is: "+th.getCounter());
    }
}

在上述情况下,“返回”在哪里返回

案例1:我检查了是否在catch块中保留了“return”关键字,最后执行的行再次来自主方法,即“按enter键停止计数器…”

案例2:如果省略return语句,那么main中最后执行的一行是“System.out.println”(“计数器的值是”+th.getCheker())

我的问题是,为什么在第一种情况下还要行“System.out.println(“计数器的值是”+th.getCheker());”没有被执行吗

我认为在调用return时,控件应该从线程的“run()”方法返回到main中线程启动的位置。所以,那个时并没有在main中执行的语句现在应该执行。但是,如果我使用return语句,应用程序就要结束了。主力也回来了。之后不会执行任何语句。你能解释一下吗?我错过了什么


共 (3) 个答案

  1. # 1 楼答案

    它将结束函数,当函数返回void时,它不会返回任何内容

  2. # 2 楼答案

    您的“混淆线”将导致线程的run()方法返回。这将导致线程死亡,因为当run()返回时,线程总是死亡


    “案例1:”与“案例2:”

    你的“困惑线”包含在一个循环中。如果取出return语句,那么run()方法将不会在该点返回:它将返回while(checking)循环的顶部


    I thought while return is called the control should return from the "run()" method of the thread to the place in main from where the thread is started.

    线程不是这样工作的。新线程没有什么可返回的。main()线程的任务是执行启动新线程的语句之后的语句。当新线程的run()方法完成时,除了死之外,它没有其他事情可做

  3. # 3 楼答案

    return;将中断while循环

    你可以使用break;checking = false,你也会有同样的效果


    the last executed line again is from the main method which is "Press enter to stop the counter...."

    也许这是因为它在等待你真正按下回车键

    If I omit the return statement then the last executed line from main is "System.out.println("value of counter is "+th.getCheker());"

    那行代码和你的问题不匹配

    should return from the "run()" method of the thread to the place in main from where the thread is started

    不,它是一个独立的线程,在后台并行执行。只是碰巧打印到同一个输出流,所以很难看到


    线程使用自己的调用堆栈在自己的线程中执行。当你从run()开始return时,它会结束,因此会停止它,并且不会在代码中“返回到其他地方”

    如果要卸下扫描仪,则应该运行两个打印语句