crusader
crusader

Reputation: 93

How can I make this thread stop

So that is my question how can I make the thread stop, I am not very proficient in threads but the little information I have read tell me that this should work.

public class testestes {
    static volatile boolean key;

    public static void main (String []args)
    {
        key=true;
        Thread thread=new Thread(new Runnable()
        {
            public void run()
            {
                while(key)
                {
                    System.out.println("running");
                }
            }
        });

        thread.start();
        key=false;
    }
}

Upvotes: 0

Views: 249

Answers (5)

Thomas
Thomas

Reputation: 5094

The basic layout for doing this is to actually have a class that implements Runnable.

public class SampleThread implements Runnable
{
  private volatile boolean stopFlag = false;

  public void stopThisThread()
  {
    stopFlag = true;
  }

  public void run()
  {
    while (!stopFlag)
    {
      //doStuff
    }
  }
}

Then elsewhere

SampleThread sample = new SampleThread();
new Thread(sample).start();
//Then when you want to kill it...
sample.stopThisThread();

Upvotes: 0

Konrad Reiche
Konrad Reiche

Reputation: 29493

I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

Certain blocking library methods support interruption.

Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

public void run() {

   try {
      while(!Thread.currentThread().isInterrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)
      /* Allow thread to exit */
   }

}

public void cancel() { interrupt(); }

Source code taken from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

There is also a poorly named static method interrupted which clears the interrupted status of the current thread.

Upvotes: 2

Nick King
Nick King

Reputation: 47

I believe you may want to look into interrupting the thread with Thread.interrupt(). There's a good article about it in the Java Tutorials.

The answers suggesting a boolean flag are equally correct. In either case, you're going to check in some conditional statement somewhere to see if your thread should terminate. The condition for termination could be either that the thread was interrupted or its boolean flag was set (depending on which implementation you choose).

One final word of warning: never use Thread.stop(). It is deprecated for a good reason. See here for a good explanation.

Upvotes: 0

phatfingers
phatfingers

Reputation: 10250

The technique posed in your simplified code should work. I can confirm at least that it works on my desktop. Have you tested the simplified version locally? Maybe there's something going on in your actual version that isn't being represented here, like a use of a non-static variable or an additional condition that must also be met.

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143876

You want to call thread.start();, NOT thread.run();. run() won't fork.

Also, it's probably going to be the case that you won't see any "running" output because you're immediately setting key to false after you fork so when the forked thread enters run(), key is already false.

Upvotes: 1

Related Questions