1

I want to implement a timer in my android game using following code. This code runs certain code after every second.

final Handler handler = new Handler(); 
    Runnable runable = new Runnable() { 

        @Override 
        public void run() { 
            try{
                //task to be done
                handler.postDelayed(this, 1000);
            }
            catch (Exception e) {
                // TODO: handle exception
            }
            finally{
                //task to be done
                handler.postDelayed(this, 1000); 
            }
        } 
    }; 
    handler.postDelayed(runable, 1000); 

The handler is created in UI thread. Will such an infinite loop block the thread ? If not why not ?

user3293494
  • 609
  • 1
  • 9
  • 21
  • 1
    it will block the thread for the time needed to run "task to be done" ... then for ~1 sec thread will be free for other stuff ... – Selvin May 23 '14 at 08:19

1 Answers1

1

There is no loop and control returns to the UI thread looper that processes the message queue. It won't block the UI thread.

However, you're congesting the UI thread in other ways. Each invocation of the runnable re-posts itself twice: once in try and second time in finally, therefore effectively doubling the number of events in the message queue each second. Eventually the UI thread won't be able to do any useful work processing other events.

laalto
  • 150,114
  • 66
  • 286
  • 303