0

I know the 2 rules that UI thread shouldn't blocked and udating ui in only UI thread.

So I know roughly why using Thread.sleep() with setText() doesn't work. (Because call Thread.sleep() blocks the UI thread !!)

But...why??

Imagine below code, I clicked a button to start timer to represent number every 50 milli seconds.

public void onTimerClicked(View v){
    TextView tv = (TextView) findViewById( .. )
    for( int i = 1; i <= 10; i++ ){
        Thread.sleep(50) // in  milil seconds
        tv.setText(String.valueOf(i));
    }
}

I already know when I click a button, after I get some freezing time only displays '10' on a text view. But why?? If UI thread encounter tv.setText(..) , it doesn't work for updating UI immediately?? or queueing the task( updating text view UI ) to message queue on main thread?? Then what is the criteria for queueing to message queue instead running the code immediately when it faces.

also, if setting text view with numbers are all queued, then after all sleeping is end. Does UI update all the task very fast?? is it reason that I can only last update ??

I am really curious about how UI thread works for dealing with UI datating internally.. but there are rarely information or explanation about this.

please let me understand !!

Thanks for reading

  • 1
    Because `onTimerClicked` is called on UI thread ... you blocked it with loop inside `onTimerClicked` ... so there is no time to redraw (because it is also done on UI thread which is currently blocked) ... UI thread just take a job from message queue and do it ... so it cannot do 2 things at the same time – Selvin Feb 07 '17 at 16:28
  • @Selvin Thank you for replying. But that's not what I wanted. Actually I found good answer , http://stackoverflow.com/questions/16595467/android-textview-settext-invoked-returned-before-thread-sleep-blocks-until . This described very well that I really wanted to know – JEONGHUN CHAE Feb 08 '17 at 01:43

0 Answers0