简体   繁体   English

Android Handler实例线程安全

[英]Android Handler instance thread safety

Is Android Handler class instance itself thread safe? Android Handler程序 class 实例本身是线程安全的吗?

For example, is it safe to post from multiple threads to the main thread with the example code below, or one has to instantiate two handlers (one in each thread)?例如,使用下面的示例代码从多个线程发布到主线程是否安全,或者必须实例化两个处理程序(每个线程中一个)?

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

new Thread(new Runnable() {
    public void run() {
        Runnable runnable1 = new MyRunnable();
        singleHandler.postDelayed(runnable1, 100);
    }
}).start();

new Thread(new Runnable() {
    public void run() {
        Runnable runnable2 = new MyRunnable();
        singleHandler.postDelayed(runnable2, 150);
    }
}).start();

There's a similar question on SO, but it deals with thread safety of message processing (not posting), which is slightly different Are android handlers thread safe? SO上有一个类似的问题,但它处理消息处理的线程安全(不是发布),这略有不同android处理程序线程安全吗?

Yes, it completely fine to post from any numbers of threads to single instance of Main Handler.是的,从任意数量的threads发布到Main处理程序的单个实例完全没问题。 As @Onik mentioned Handler job is to deliver the message to mentioned Looper , and there is at any given time only one MainLooper for your process.正如@Onik 提到的 Handler 的工作是将消息传递给提到的Looper ,并且在任何给定时间只有一个MainLooper用于您的流程。 So a single instance of handler will post to that.因此,处理程序的单个实例将发布到该实例。 To support answer, if you look at View.Java , it initialises one mHandler inside AttachInfo and pretty much uses that to post all the messages to MainLooper .为了支持答案,如果您查看View.Java ,它会在AttachInfo中初始化一个mHandler并几乎使用它将所有消息发布到MainLooper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM