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

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

    First of all, you are not starting any thread here! You should create a new thread and pass your confusingly named thread1 Runnable to it:

    thread1 t1 = new thread1();
    final Thread thread = new Thread(t1);
    thread.start();
    

    Now, when you really have a thread, there is a built in feature to interrupt running threads, called... interrupt():

    thread.interrupt();
    

    However, setting this flag alone does nothing, you have to handle this in your running thread:

    while(!Thread.currentThread().isInterrupted()){
        try{        
            Thread.sleep(10);
        }
        catch(InterruptedException e){
            Thread.currentThread().interrupt();
            break; //optional, since the while loop conditional should detect the interrupted state
        }
        catch(Exception e){
            e.printStackTrace();
        }
    

    Two things to note: while loop will now end when thread isInterrupted(). But if the thread is interrupted during sleep, JVM is so kind it will inform you about by throwing InterruptedException out of sleep(). Catch it and break your loop. That's it!


    As for other suggestions:

    • About Thread.stop():

    Deprecated. This method is inherently unsafe[...]

    • Adding your own flag and keeping an eye on it is fine (just remember to use AtomicBoolean or volatile!), but why bother if JDK already provides you a built-in flag like this? The added benefit is interrupting sleeps, making thread interruption more responsive.

提交回复
热议问题