• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread - Stop/Destroy

 
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic