android 处理程序线程安全吗? [英] Are android handlers thread safe?
问题描述
我正在重构一个 Android 项目.我偶然发现了一段我认为非线程安全的奇怪代码.我认为这个例子会导致随机崩溃是否正确?
I am doing some refactoring into an Android project. I have stumble upon a strange piece of code that I consider non thread-safe. Am I correct to think that this example could cause a random crash?
public class SampleClass
{
Object foo = new Object();
// foo can be set to null in the main thread
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if (foo == null)
return;
Thread.sleep(600,0);
// There is a chance foo has been set to null while the thread was asleep...
foo.doSomething();
}
}
}
尽管我听说处理程序在默认情况下是线程安全的,但似乎我需要在 handleMessage 函数内以及任何可以将 foo 设置为 null 的地方放置同步块.
Even though I hear that handler are thread safe by default, it seems that I would need to place synchronized blocks inside the handleMessage function and any place where foo could be set to null.
推荐答案
Looper 只有在线程处于唤醒状态时才能将 Message 传递给处理程序.'foo' 是一个私有字段,如果你只从那个方法访问它 - 那很好
Looper can deliver Message to handler only when thread is awake. 'foo' is a private field, and if you access it only from that method - that is fine
这篇关于android 处理程序线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!