简体   繁体   English

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

[英]Where does “return” returns if used inside the catch block of an InterruptedException in a thread?

It might be very simple question for you but I would much appreciate if you please help to clear my doubt on this. 对您来说,这可能是一个非常简单的问题,但是如果您能帮助我消除对此的疑问,我将不胜感激。

Suppose I created a thread that uses a sleep() method and from my main method I am interrupting it. 假设我创建了一个使用sleep()方法的线程,并且从我的main方法中中断了该线程。

Here is my code fragment 这是我的代码片段

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

Where does the "return" return in the above case? 在上述情况下,“返回”在哪里返回?

Case 1 : I checked if I keep the "return" keyword in the catch block, the last executed line again is from the main method which is "Press enter to stop the counter...." 情况1:我检查是否在catch块中保留了“ return”关键字,最后执行的行还是来自主方法“按Enter停止计数器...”。

Case 2: If I omit the return statement then the last executed line from main is "System.out.println("value of counter is "+th.getCheker());" 情况2:如果我省略return语句,则最后一次从main执行的行是“ System.out.println(” counter的值为“ + th.getCheker());”

My question is, why in the first case also line "System.out.println("value of counter is "+th.getCheker());" 我的问题是,为什么在第一种情况下也是“ System.out.println(“ counter的值为” + th.getCheker());“行? is not executed? 不执行?

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. 我以为在调用return时,控件应从线程的“ run()”方法返回到线程开始处在main中的位置。 So, statements that are not executed in main by then, should be executed now. 因此,到那时尚未在main中执行的语句应立即执行。 But it seems if I use the return statement the application is ending. 但是似乎如果我使用return语句,应用程序将结束。 The main is also returning. 主力也回来了。 No statement is getting executed after that. 此后没有任何语句被执行。 Could you please explain that? 你能解释一下吗? What I am missing? 我缺少什么?

Your "line of confusion" will cause the run() method of the thread to return. 您的“混乱之线”将导致线程的run()方法返回。 That will cause the thread to die because threads always die when run() returns. 这将导致线程死亡,因为线程总是run()返回时死亡。


"Case 1:" vs. "Case 2:" “案例1”与“案例2”

Your "line of confusion" is contained within a loop. 您的“混乱之线”包含在一个循环中。 If you take out the return statement, then the run() method won't return at that point: It will go back to the top of the while(checking) loop. 如果删除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. 我以为在调用return时,控件应从线程的“ run()”方法返回到线程开始处在main中的位置。

That's not how threads work. 那不是线程的工作方式。 THere's nothing for the new thread to go back to. 没有什么可以让新线程返回。 It's the main() thread's job to execute the statements that comes after the one that started the new thread. main()线程的工作是执行启动新线程的语句之后的语句。 When the new thread's run() method is finished, there's nothing left for it to do except die. 当新线程的run()方法完成时,除了die之外,别无他法。

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

return; will break the while loop. 将打破while循环。

You can use break; 您可以使用break; or checking = false and you'd have the same affect. checking = false会产生相同的影响。


the last executed line again is from the main method which is "Press enter to stop the counter...." 最后执行的行还是来自主方法“按回车以停止计数器...”。

Maybe that is because it is waiting for you to actually press Enter ? 也许是因为它正在等您实际按Enter键

If I omit the return statement then the last executed line from main is "System.out.println("value of counter is "+th.getCheker());" 如果我省略return语句,那么从main执行的最后一行是“ System.out.println(”计数器的值是“ + th.getCheker());”。

That line of code doesn't match your question... 该行代码与您的问题不符...

should return from the "run()" method of the thread to the place in main from where the thread is started 应该从线程的“ run()”方法返回到线程开始处在main中的位置

Nope, it's a separate Thread, it executes parallelly in the background. 不,这是一个单独的线程,它在后台并行执行。 You just happen to be printing to the same output stream, so that's hard to see. 您只是碰巧要打印到相同的输出流,所以很难看到。


The Thread executes in its own thread with its own call stack. 线程在具有自己的调用堆栈的线程中执行。 When you return from run() , it ends, therefore stopping it, and it doesn't "return to somewhere else" in your code. 当您从run() return ,它结束,因此将其停止,并且它不会在代码中“返回到其他位置”。

Both print statements you have should run if you would remove the Scanner. 如果要删除扫描仪,则应同时运行两个打印语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Interruptedexception 的不间断捕获块 - Uninterrupted catch block for Interruptedexception 在哪里使用synchronized块捕获Object.wait()的InterruptedException? - Where to catch InterruptedException for Object.wait() with synchronized block? Java 线程 InterruptedException 块未执行 - Java thread InterruptedException block not executing 在InterruptedException的catch子句中中断线程的原因是什么? - What is the reason for interrupting the thread in the catch clause of InterruptedException? 无限的Thread.sleep而lambda中的循环不需要'catch(InterruptedException)' - 为什么不呢? - Thread.sleep inside infinite while loop in lambda doesn't require 'catch (InterruptedException)' - why not? 在线程安全 Singleton 中,返回是否必须在同步块内 - In a Thread Safe Singleton does the return have to be inside the synchronized block InterruptedException没有捕获? - InterruptedException not catch? 捕获InterruptedException时JVM是否需要退出 - Does JVM need to exit when catch InterruptedException 这个catch块内发生了什么? - What does happen inside this catch block? 为什么要捕获InterruptedException来调用Thread.currentThread.interrupt()? - Why would you catch InterruptedException to call Thread.currentThread.interrupt()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM