What will happen if you call interrupt() on a sleeping thread?

痴心易碎 提交于 2019-12-11 10:53:05

问题


I have a thread, and on run() I call sleep(). What will happen if I interrupt this thread?

MyThread extends Thread{
    public void run(){
          try{
             sleep(1000000);
          } catch(InterruptedException e) {//}
    }    
}

I want to clarify the following:

  • If the thread is not yet started, calling interrupt() would do nothing, right?
  • If the thread is started, and is now sleeping, calling interrupt() while sleeping will throw an InterruptedException; and thus, goes to catch() and then ends the thread, right?

回答1:


1) Thread.interrupt API: Interrupting a thread that is not alive need not have any effect.

2) In your example the interrupted thread will enter catch block then leave run method and terminate



来源:https://stackoverflow.com/questions/15225579/what-will-happen-if-you-call-interrupt-on-a-sleeping-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!