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 takes about a minute, but due to some expected problem, it is running for ever. can we stop that thread ?
public class thread1 implements Runnable { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub thread1 t1 = new thread1(); t1.run(); } @Override public void run() { // TODO Auto-generated method stub while(true){ try{ Thread.sleep(10); } catch(Exception e){ e.printStackTrace(); } } } }
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected.
The only way to stop a thread asynchronously is the stop() method.
Yes, it doesn't. I guess it can be confusing because e.g. Thread. sleep() affects the current thread, but Thread. sleep() is a static method.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
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:
Deprecated. This method is inherently unsafe[...]
AtomicBoolean
or volatile
!), but why bother if JDK already provides you a built-in flag like this? The added benefit is interrupting sleep
s, making thread interruption more responsive. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With