• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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: 24204
44
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
 
Warning! Way too comfortable! Do not sit! Try reading this tiny ad instead:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic