Judgment handler.postDelayed (new Runnable) is running in the main thread

Project encountered a problem: If the handler is an object in the main thread, then if a call handler.postDelayed (new Runnable ()), Runnable in the run () in the sub-thread logic will not be executed. I will be notified by eventbus back to the main thread, the main thread to call handler.postDelayed (new Runnable ()) to take effect

So how do we judge handler.postDelayed (new Runnable ()) is running in the main thread?

A: new Runnable () attached to create Handler thread, that is, if Handler created thread is the main thread is runnable will need to perform on the main thread; if a thread is created Handler child thread is runnable will need in the child thread carried out.

In the UI thread (that is, the main thread) in the print thread ID to verify:

System.out.println("主线程为== " + Thread.currentThread().getId());  

UI thread calls the new Handler () postDelayed print running thread ID.:

new Handler().postDelayed(new Runnable() {  
    @Override  
    public void run() {  
        System.out.println("Handler 线程为 ==" + Thread.currentThread().getId());  
    }  
}, 5000);  

Finally, print the following:

 主线程为== 1  
 Handler 线程为 == 1  

You can see, they both programs are running in the main thread.
Google's official explanation is:

The runnable will be run on the thread to which this handler is attached.

It is said that the open runnable this handler will run in the attached thread, and this handler is created in the UI thread (that is, the main thread), the so runnable naturally attached to the main thread.

postDelayed (new Runnable ()) is not re-generate a new thread.

Guess you like

Origin blog.csdn.net/weixin_43115440/article/details/93005717