How to timeout a thread

后端 未结 17 1113
时光说笑
时光说笑 2020-11-22 01:01

I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 01:48

    BalusC said:

    Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().

    But if you replace Thread.sleep(4000); with for (int i = 0; i < 5E8; i++) {} then it doesn't compile, because the empty loop doesn't throw an InterruptedException.

    And for the thread to be interruptible, it needs to throw an InterruptedException.

    This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.

    Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]

提交回复
热议问题