How to stop a thread that is running forever without any use

后端 未结 6 2116
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 14:58

In the below code, i have a while(true) loop. considering a situation where there is some code in the try block where the thread is supposed to perform some tasks which take

6条回答
  •  我在风中等你
    2020-12-07 15:52

    The proper way to stop a thread is to interrupt it (stop() is deprecated and may have nasty side effects):

    t1.interrupt()
    

    This will cause an InterruptedException to be thrown by methods like Thread.sleep() or Object.wait().

    Then just add a catch block for this exception and simply break out of the while loop.

    EDIT: I now realised that your infinite loop is running within the main thread, there's no thread created by your code, it's just run()ning a Runnable. You need to call Thread.start() at some point to spawn a new thread.

提交回复
热议问题