如果在线程中中断异常的捕获块中使用"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"关键字,最后执行的行再次来自主方法,即"按回车停止计数器......">

情况 2:如果我省略 return 语句,那么 main 中最后执行的行是"System.out.println("计数器的值是 "+th.getCheker());"

我的问题是,为什么在第一种情况下还行"System.out.println("计数器的值是"+th.getCheker());"不执行?

我认为虽然调用返回,但控件应该从线程的"run()"方法返回到线程启动的 main 中的位置。因此,当时未在 main 中执行的语句现在应该执行。但是似乎如果我使用 return 语句,应用程序就会结束。主要也回来了。之后不会执行任何语句。你能解释一下吗?我错过了什么?

您的"混乱行"将导致线程的run()方法返回。 这将导致线程死亡,因为线程总是在返回时死亡run()

"案例

1:"与"案例 2:">

你的"混乱线"包含在一个循环中。 如果取出return语句,则run()方法此时不会返回:它将返回到while(checking)循环的顶部。


我认为虽然调用返回,但控件应该从线程的"run()"方法返回到线程启动的 main 中的位置。

这不是线程的工作方式。 对于新线程来说,没有什么可以回去的。 main() 线程的工作是执行启动新线程的语句之后的语句。 当新线程的run()方法完成后,除了死亡之外,它没有什么可做的了。

return;将打破while循环。

您可以使用break;checking = false,并且会产生相同的影响。


最后执行的行再次来自主方法,即"按回车停止计数器...">

也许那是因为它正在等待您实际按Enter键?

如果我省略了 return 语句,那么 main 中最后一个执行的行是"System.out.println("计数器的值是"+th.getCheker());">

那行代码与您的问题不匹配...

应该从线程的"run()"方法返回到线程启动的主位置

不,它是一个单独的线程,它在后台并行执行。您只是碰巧打印到相同的输出流,因此很难看到。

线程在其自己的

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

如果要删除扫描仪,则应运行两个打印语句。

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

最新更新