官方文檔明確指出,SharedPreferences不支持多線程,進程也是不安全的
如果想要實現線程安全需重新實現其接口,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
private
static
final
class
SharedPreferencesImpl
implements
SharedPreferences {
...
public
String getString(String key, String defValue) {
synchronized
(
this
) {
String v = (String)mMap.get(key);
return
v !=
null
? v : defValue;
}
}
...
public
final
class
EditorImpl
implements
Editor {
public
Editor putString(String key, String value) {
synchronized
(
this
) {
mModified.put(key, value);
return
this
;
}
}
...
}
}
|