John Roberts
John Roberts

Reputation: 5986

Why is the thread being created multiple times?

I have the following method I'm using to run a continuous thread:

public void createAndStartCountDownThread(){
    final Handler handler = new Handler();


    countDownThread=new Thread(new Runnable() {
        public void run() {
            int timeToBlink = 1000;
            try{Thread.sleep(timeToBlink);}catch (Exception e) {}
            handler.post(new Runnable() {
                public void run() {
                    if(isCountDownThreadRunning==0)
                        return; 
                    if(secondsUntilFinished!=0)
                        secondsUntilFinished--;

                    if(secondsUntilFinished==0)
                        onFinish();
                    else{

                        createAndStartCountDownThread();

                    }
                }
            });

        }
    });

    countDownThread.start();

}

Basically all this does is countdown a timer. However, the problem is that, if I call this method too often, it seems that multiple copies of this thread are created, as the timer starts moving twice or three times as fast. I don't understand why this happens - it seems that I'm re-assigning the existing countDownThread, so a new one shouldn't be generated. What am I doing wrong?

Upvotes: 1

Views: 81

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93708

Your run function in the handler calls createAndStartCountDownThread(), which creates a new thread and calls start on it. So each thread will post something to the handler, which will create a new thread. So yes, this function will spawn lots of threads.

I'm not sure what you're trying to do, but this is the wrong way. If you want a timer, use a timer or an Alarm. If you want to create a continuous thread, you want one thread with a loop (so the thread doesn't exit run and terminate prematurely). If you want to just be woken up later (and later is realtively soon) just use a Handler.

Edit:

If you're trying to implement blinking behavior, I'd suggest just using a single handler with a message posted to it via postMessageDelayed. This will run the handler runnable in the specified amount of time later. No threads involved, everything is on the UI thread so you can alter your UI from it.

Upvotes: 3

Related Questions