Thread stopping.

How do I stop? The method Thread.stop() is unsafe, and Tread.destroy() just destroys the thread without any clean-up.
What should I do, because this is thread is ran very often! How do I cancel it again, and clean up?

Did you bother to read the documentation?

http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

What is it you want to forcibly stop? And why doesn’t the above solution work for you?

I see no methods that stops a thread. I dont want to have my threads running forever :stuck_out_tongue:

http://www.catb.org/~esr/faqs/smart-questions.html


boolean keepRunning = true;

public void run()
{


while (keepRunning)
   {

   ....
   }


}


public void stopMyThreadPlease()
{
keepRunning = false;
}


You might also want to check the links OrangyTangy posted.

Omg this one is extensive, but probably I’ll give it a look :smiley: (interesting)

Thank you, I was just not sure if I should manually stop the thread when it has no more use but appearently it does that by itself.

Quick extra - call interrupt() too in the stopMyThreadPlease() method - that way if you’re blocked on IO or a monitor it’ll get interrupted and you can check the flag.

Cas :slight_smile:

Using a boolean is OK, but to prevent having multiple threads running at the same time, I advice to use the following official method:

Thread thread;

public void start() {
  if (thread != null) {
    thread = new Thread(this);
    thread.start();
  }
}

public void stop() {
  thread = null;
}

public void run() {
  Thread currentThread = Thread.currentThread();
  while (this.thread == currentThread) {
    // do stuff
    ...

    // sleep as needed
    e.g. Thread.sleep(100);
  }
}

and the boolean should be volatile.