官方文档明确指出,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
;
}
}
...
}
}
|