• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can i stop the particular thread before completing its life time

 
Dhineshkumar raj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one tell me how can i stop the particular thread before completing its life time???
Just go through the following code.

class TestThread{
public static void main(String[] args){
RunnableThread runnableThread = new RunnableThread ();
Thread thread = new Thread(runnableThread );
thread.start();
}
}

1. class RunnableThread implements Runnable{
2. public void run(){
3. for(int i = 0; i < 100; i++){
4. System.out.println(i);
5. if(i==50) Thread.stop();
6. }
7. }
8. }

The above code its correct. But my doubt is Thread.stop() is Deprecated method then what is alternative solution to stop or kill this thread and make it dead state???

Note : I can use as break & return also at line number 5

For example,
if(i==50) break; (or) if(i==50) return;

Apart from this is there any other solutions to make its dead state ???

Thanks Regards
Dhineshkumar R
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed, you should not use Thread.stop().

If you want to terminate the thread from inside of the for loop, you could just use "if (i==50) break;". That will cause the run method (and thus the thread) to terminate right away.

If you want to terminate it from some other class, the way to do it is to set some boolean value in the thread class. The thread would then check for this every so often (in this case maybe once per loop iteration), and if it is set, stop what it is doing, and let the run method finish.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And, for anyone who's not sure...

Thread.stop() is "more" deprecated than some other deprecated methods. Whereas some other deprecated methods basically work correctly, Thread.stop() and related methods are irrevocably broken in their whole concept. Although it will often appear to work OK, any application using it is very likely to suffer unexpected deadlocks etc.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!