Thread currentThread=Thread.currentThread();
public void run()
{
while(!shutdown)
{
try
{
System.out.println(currentThread.isAlive());
Thread.interrupted();
System.out.println(currentThread.isAlive());
if(currentThread.isAlive()==false)
{
shutdown=true;
}
}
catch(Exception e)
{
currentThread.interrupt();
}
}
}
});
thread.start();

- 94,330
- 19
- 181
- 276

- 279
- 1
- 3
- 3
-
could you check the above code and help me to kill the thread – greeshma May 06 '11 at 17:55
-
2See this post http://forward.com.au/javaProgramming/HowToStopAThread.html – Bala R May 06 '11 at 17:55
-
3Uh...is this even compilable code? – mre May 06 '11 at 17:58
-
Have a look at [Best Practice for killing a JavaME 1.2 thread?](http://stackoverflow.com/q/837948/609436), it may help. – Piccolomomo May 06 '11 at 17:57
-
`Thread.currentThread().isAlive()` can never be false, by definition. The code is pointless. – user207421 May 31 '17 at 17:43
3 Answers
The alternative to calling stop is to use interrupt to signal to the thread that you want it to finish what it's doing. (This assumes the thread you want to stop is well-behaved, if it ignores InterruptedExceptions by eating them immediately after they are thrown and doesn't check the interrupted status then you are back to using stop().)
Here's some code I wrote as an answer to a threading question here, it's an example of how thread interruption works:
public class HelloWorld {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
thread.start();
System.out.println("press enter to quit");
System.in.read();
thread.interrupt();
}
}
Some things to be aware of:
Interrupting causes
sleep()
andwait()
to immediately throw, otherwise you are stuck waiting for the sleep time to pass.Note that there is no need for a separate boolean flag.
The thread being stopped cooperates by checking the interrupted status and catching InterruptedExceptions outside the while loop (using it to exit the loop). Interruption is one place where it's ok to use an exception for flow control, that is the whole point of it.
Setting interrupt on the current thread in the catch block is technically best-practice but is overkill for this example, because there is nothing else that needs the interrupt flag set.
Some observations about the posted code:
The posted example is incomplete, but putting a reference to the current thread in an instance variable seems like a bad idea. It will get initialized to whatever thread is creating the object, not to the thread executing the run method. If the same Runnable instance is executed on more than one thread then the instance variable won't reflect the right thread most of the time.
The check for whether the thread is alive is necessarily always going to result in true (unless there's an error where the currentThread instance variable is referencing the wrong thread),
Thread#isAlive
is false only after the thread has finished executing, it doesn't return false just because it's been interrupted.Calling
Thread#interrupted
will result in clearing the interrupt flag, and makes no sense here, especially since the return value is discarded. The point of callingThread#interrupted
is to test the state of the interrupted flag and then clear it, it's a convenience method used by things that throwInterruptedException
.

- 1
- 1

- 94,330
- 19
- 181
- 276
-
@Nathan: +1, if I had seen this answer, I wouldn't have even bothered writing one of my own! gg – mre May 06 '11 at 18:33
-
1First of all, this code assumes that a sleep or other Interruptible blocking call is going to be used. This need not be the case. The code could be to do some complicated calculations. Using Thread interrupts need more care. Some IOs can also be interrupted, if there are multiple such IOs, we may need to clean up objects carefully, etc. I would suggest using a flag variable as a safer option generally. – Raze May 06 '11 at 18:37
-
@Raze: wouldn't simply catching blocking I/O interrupts and interrupting the current thread suffice? – mre May 06 '11 at 18:42
-
It will definitely stop the thread, but this of this in the `run()` method: `{ try { while(...) {byte[] input = getChunkFromNetworkWhichHasCriticalData(); alertUser(input); } } catch(ClosedByInterruptException cbie) {...} }`. Two points: Not all IO calls are interrupted, and so it may never exit. If IO call which will interrupt is called, then handling partially obtained data may be difficult. In many cases, like video streaming, this is not a concern. If there are multiple interruptible points in the code, it may get even more complex. – Raze May 06 '11 at 19:07
-
1@Raze: care is definitely called for. that is why I left the Thread.currentThread().interrupt() in the example, to demonstrate making sure the interrupt flag is maintained. In any case, for the OP's purposes I don't think the flag is necessary, though it doesn't hurt anything and your example is well-implemented. – Nathan Hughes May 06 '11 at 19:10
-
The points being: 1. There has to be calls in the code which are interruptible. 2. If handling code/data which has partially run/obtained/sent is important, design of the code has to be done carefully. When this kind of interruption and interrupt handling is not requried, it can be avoided. But there are many cases where using interrupts properly is recommended and is more efficient. – Raze May 06 '11 at 19:14
-
And the example quoted by @greeshma doesn't have a sleep in it, and I didn't make any assumptions. Besides, I have seen people I know implement audio multi casting with multiple threads, using interrupts to exit, and failing to flush the audio buffer in some cases, which leaves small bits of audio looping forever till the program exits. – Raze May 06 '11 at 19:18
-
@NathanHughes I came across your answer and it's pretty helpful, it's just that I can't understand the reason of calling interrupt again in the catch? Why would the same thread call interrupt again? – Abidi Sep 30 '13 at 08:31
-
@Abidi: in this case it doesn't matter. if you had nested components that all had to respond to interruption then you would need to do this to make sure everybody sees the interrupt. – Nathan Hughes Sep 30 '13 at 16:19
-
This is a great answer! I have always implemented a separate flag but this makes much more sense. As far as closing resources properly goes, it is not a threading issue but an error handling issue. IO should be closed in a finally block not a try or catch block. This is so often messed up jdk7 came out with try-with-resources statements. – John Mercier Jun 08 '15 at 16:13
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();

- 43,520
- 33
- 120
- 170
-
2+1, people like to roll their own (boolean) but you have to make it volatile and blar blar blar... using a standard interruption policy like isInterrupted feels more elegant :D – Toby May 18 '11 at 08:30
-
if I call threat.interrupt(); without calling Thread.sleep(1000) what will happen, and is this safe? – Lovekush Vishwakarma Nov 23 '18 at 11:09
-
@LovekushVishwakarma https://docs.oracle.com/javase/10/docs/api/java/lang/Thread.html#interrupt() – mre Nov 26 '18 at 15:49
Good way to do it would be to use a boolean flag to signal the thread.
class MyRunnable implements Runnable {
public volatile boolean stopThread = false;
public void run() {
while(!stopThread) {
// Thread code here
}
}
}
Create a MyRunnable instance called myrunnable, wrap it in a new Thread
instance and start the instance. When you want to flag the thread to stop, set myrunnable.stopThread = true. This way, it doesn't get stopped in the middle of something, only where we expect it to get stopped.
-
Using a flag for cancellation can be dangerous if combined with blocking queue. – Luke Jun 06 '16 at 21:04
-
@Luke, are you talking about cases where thread might not exit because it is waiting on a queue? – Raze Jun 07 '16 at 11:25
-
yeah basically if you have a blocking operation like queue.put within the while loop and your queue is full and all the consumers of the queue have finished then even if you set the flag to stop your task won't finish. – Luke Jun 07 '16 at 19:02
-
@luke, That's true for any operation that uses Object.wait or one of the many NIO calls, in which case Nathan's answer can be used with or without adding the flag as the case may be. However that may not work in a system where you the class doesn't have permission to interrupt (rare, but I've been there once), and more importantly, edge cases where thread hasn't started yet. – Raze Jun 08 '16 at 00:19
-
@Luke can you tell me how to stop thread in the situation that you wrote? I mean when thread is blocking on queue and should be stoped. – user3740179 Feb 10 '22 at 07:15
-
@user3740179 in that case you can use thread's interrupt method (See Nathan's answer ). If there are multiple calls which will do a wait, you should check isInterrupted after each such call – Raze Mar 23 '22 at 19:12