Handler created in main thread acts like it is on another thread

你离开我真会死。 提交于 2019-12-24 14:09:11

问题


As google says:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

And i expect when i create a Handler in main thread (UI thread) it attached to this thread so it cause to freeze ui till end it's task. But in test this not happen and it is acts like it is on a backgound thread and do his task parallel. I used to create Handle like this:

 Handler mainHandler = new Handler(Looper.getMainLooper());

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 35000; i++) {
                log.i(TAG,"log in Handler:"+i);
            }}
    };

    mainHandler.post(runnable);
    log.i(TAG,"log outSide");

In mainActivity (so handle should bound to Main thread). So what is the problem with this or am i create the handler in wrong way?

Some friends notice that doSomthing() is not complicated enough but why we see "log outSide" before "log in Handler:" if they are in a same thread.


回答1:


Actually, It's working as you expected, Your handler is currently associated with your main thread because it is created in it and your task is also running on the same. Try to add Thread.sleep(1000) method inside your for loop then you will see the freeze in your UI. Your current code runs with a complexity of O(1) since your N is constant, and your phone is capable enough to run this in a fraction of a second that's why you are not observing any freeze in your UI during the test.



来源:https://stackoverflow.com/questions/51062798/handler-created-in-main-thread-acts-like-it-is-on-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!