Waking up a sleeping thread - interrupt() versus “splitting” the sleep into multiple sleeps

前端 未结 4 660
温柔的废话
温柔的废话 2021-02-10 10:40

This requirement came up in my Android app, but it applies to Java in general. My app \"does something\" every few seconds. I have implemented this as follows (just relevant sni

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-10 11:01

    You call interrupt() on the thread that's sleeping and it will throw an InterruptedException which you handle in your catch block. Then you have your new interval and you can loop around and go back to sleep. If you catch and handle the InterruptedException nothing further happens.

    Let me provide a couple of links of examples of creating and interrupting threads, as from your comments you seem to be missing some important ideas. Please review these carefully and then you should understand the standard way to do what you are asking for.

    http://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

提交回复
热议问题