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

后端 未结 6 2133
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    Move the catch interrupt to outside the loop. This doesn't require any more lines of code, it just handles interrupts correctly i.e. the action is interrupted.

    public void run() {
        try{        
            while(true) {
                Thread.sleep(10);
            }
        } catch(InterruptedException e){
            System.out.println("Thread interrupted"));
        }
    }
    

提交回复
热议问题