How to stop a Runnable thread or "interface"

I need to stop this code anyway, is there any way to do this. I don't fit in with the topics if someone can answer the question and post a link to where you can learn threads, but not at the beginner level. Ive read a lot of books on java. The basics seem casual, except for files, BufferedWriters and stuff. So anything that could fine tune the basics or where to go from there. sorry i have a question in the question. :)

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



source to share

2 answers

There is only one way to properly stop the thread: from this thread code, leaving the run () method. The most popular ways to achieve this are:

  • Flying flag - useful when your thread is running on cpu

    volatile boolean stop = false
    void run() {
        if (stop) return;
        if (stop) return;

  • interruption - when your thread mostly sleeps on padlocks

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

As a consequence, if you call library code that takes a long time and does not respond to interrupt (), that code cannot be interrupted correctly to stop the thread in which it is running.



Themes in Java currently poll the flag to see if the thread has been interrupted . When called interrupt()

on a thread, the function Thread.interrupted()

will return true

. Therefore, you can work as long as it Thread.interrupted()

returns false


while (!Thread.interrupted()){




All Articles