| Author |
Using interupt to stop the Thread
|
Ravi Kiran Va
Ranch Hand
Joined: Apr 18, 2009
Posts: 2234
|
|
I want to stop the Thread after executing certain lines of code .
If I use Thread.interrupt(); , it is not stopping .
But if when i use Thread.stop() , it is stopping but as Thread.stop() is deprecated , please let me know what is the best way to stop the Thread in between .
This is my java code :
please advice , thanks in advance .
|
Save India From Corruption - Anna Hazare.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
Assuming that that run method is the only method you're calling in the thread. You can use return. Then the method is done and so is the thread.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Mike Peters
Ranch Hand
Joined: Oct 10, 2009
Posts: 67
|
|
replace t.interrupt(); by break;
If you want to use interrupt, you must check the interrupted state of the thread.
|
Mike Peters
|
 |
Ravi Kiran Va
Ranch Hand
Joined: Apr 18, 2009
Posts: 2234
|
|
Thanks for your susggestions , i just want to know more about interupt method of Thread , so i am not using break or return .
If you want to use interrupt, you must check the interrupted state of the thread
I did not get you on the above statement .
Could you please tell , what does the above mean .
Actually the question what i want to ask his that what is the best and guaranteed way to stop a Threads execution completely .
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
The thread itself is responsible to stop itself. You should not stop a thread in the middle of his execution cycle. That can cause a lot of problems. That's why those thread methods are deprecated. A thread can check it's state by Thread.interrupted() and should then do a proper stop. Some of the thread methods throw interruptedException and then you should do the same.
|
 |
Ravi Kiran Va
Ranch Hand
Joined: Apr 18, 2009
Posts: 2234
|
|
Hi , thnaks for the reply ,
you mean to say that we must this way :
Thread t = Thread.currentThread();
Thread.State state = t.getState();
if(state.toString().equals("Interrupted"))
{
// Then what to do here ??
}
please tell me what to do in this piece of block ?? Thanks in advance .
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
That totally depends on the situation. You should just stop executing stuff. Something like:
|
 |
Ravi Kiran Va
Ranch Hand
Joined: Apr 18, 2009
Posts: 2234
|
|
|
Thanks Wouter , this was what i wanted actually . Thnaks once again .
|
 |
 |
|
|
subject: Using interupt to stop the Thread
|
|
|