Paul Trueman
Paul Trueman

Reputation: 149

How do i stop a Runnable thread or "interface"

I need to stop this code somehow is there any way to do this. I'm not in tune with threads if someone could answer the question and post a link to where you can learn threading, but not at the beginning level ive read many books on java the basics kinda come at an ease, except file changing stuff like BufferedWriters and stuff. So anything that could fine tune the basics or where to go from there. sorry i have a question in a question. :)

private final Runnable updateCircle = new Runnable() {
        @Override 
        public void run() {
            lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
            paint.setColor(lastColor);
            invalidate();
            handler.postDelayed(this, 1000);
        }
    };

Upvotes: 3

Views: 218

Answers (2)

Sergey Alaev
Sergey Alaev

Reputation: 3972

There is only one way to properly stop thread: from this thread's code, by leaving run() method. Most popular ways to achieve this:

  1. Volatile flag - useful when your thread does CPU work

    volatile boolean stop = false
    void run() {
        doComputation();
        if (stop) return;
        doAnotherComputation();
        if (stop) return;
        doMoreComputation();
    }
    
  2. interruption - when your thread mostly sleeps on locks

    void run() {
      synchronized(lock) {
        lock.wait(); //wait() will throw InterruptedException here
      }
    }
    //from another thread
    myThread.interrupt();`
    

As a consequence, if you are calling library code which takes long time and does not react to interrupt(), this code cannot be aborted correctly to stop thread it is running in.

Upvotes: 0

EvenLisle
EvenLisle

Reputation: 4812

Threads in Java currently poll a flag to see whether the thread has been interrupted. After interrupt() has been called on a thread, the Thread.interrupted() function will return true. You can therefore run as long as Thread.interrupted() returns false:

while (!Thread.interrupted()){
    ...
}

Upvotes: 1

Related Questions