3

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);
        }
    };
Paul Trueman
  • 149
  • 11
  • 1
    http://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java – Jean-François Savard Apr 21 '15 at 16:19
  • Definitely, look at the question that Jean-François Savard linked to. It's never appropriate for one thread to _force_ another thread to do something. Threads should be designed to _cooperate_ with one another. – Solomon Slow Apr 21 '15 at 16:23

2 Answers2

1

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()){
    ...
}
EvenLisle
  • 4,672
  • 3
  • 24
  • 47
0

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.

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
Sergey Alaev
  • 3,851
  • 2
  • 20
  • 35