• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread - Stop/Destroy  RSS feed

 
Dilip kumar
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All-

I was thinking that destroy method will be automatically called after completetion of run() method. But it is not working that way. Wondering what is recommended way for stopping/destroying thread after completion.

public class ThreadClass extends Thread {

/**
* Constructor for ThreadClass.
*/
public ThreadClass() {
super();
}

public static void main(String[] args) {
}

public void run() {
System.out.println("In run Method") ;
}

public void destroy() {
System.out.println("In destroy Method") ;
}

}


public class MainClass {

/**
* Constructor for MainClass.
*/
public MainClass() {
super();
}

public static void main(String[] args) {
ThreadClass TC = new ThreadClass();
TC.start();
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whatever you need to do when the thread exits, simply do it at the end of run() (in a finally block, if appropriate.) As far as the recommended way to stop a thread: a looping thread should check a flag periodically and exit if the flag becomes true. Then you can just set the flag to stop the thread.

Have a careful look at the interrupt() and interrupted() methods.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Wondering what is recommended way for stopping/destroying thread after completion.

After a thread completes, it is automatically stopped and destroyed. You don't need to do anything if a thread completes normally.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!