6

Consider this class, AnimationThread:

class AnimationThread implements Runnable {
    public void pause() {
        doAnimation = false;
    }

    public void doStart(){
        doAnimation = true;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if (doAnimation) {
            //my code
        }

        try {
            Thread.sleep(500);
        } 
        catch (InterruptedException e) {

        }
    }
}

Now I am starting this thread in onCreate of an activity (just showing rough code):

AnimationThread animRunnable = new AnimationThread();
animationThread = new Thread(animRunnable);
animationThread.start();

But run() is getting called just once (I traced a log to confirm that). I just want to know that when I started the thread why run() is not getting called repeatedly with 500 sleep. It is just called once.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
padam thapa
  • 1,471
  • 2
  • 20
  • 41

2 Answers2

12

That is how it is supposed to be.

A Thread runs by executing its run method (just once). After that it is considered done/dead/finished/completed.

If you want to loop, you have to do it yourself (inside of the run method), or use some ExecutorService to call the Runnable repeatedly.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Thanks. I got the logic. I am making sure inside run my logic code is running repeatedly. Actually in my situation i want run() to execute infinetly for my purpose so i have enclosed my logic within while(true) inside run and animation occurs based on state of doAnimation state variable. Thanks. – padam thapa Nov 18 '11 at 05:28
  • That is a common pattern. However, you probably want the thread to terminate eventually in order to shutdown the program. Or you could use a daemon thread for that. – Thilo Nov 18 '11 at 06:36
8

Of course the run() method will be executed once. If you want to repeat the statements inside the run method then you have to use loop. Take a look at TimerTask - will runs a task at a specified time or repeatedly.

EDIT:

  1. Android - Controlling a task with Timer and TimerTask?
  2. Timer task schedule
Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186