在我的Android应用程序中,我有一个单独的类,如下所示:
public enum AudioManager {
INSTANCE;
private final Object mLockLoad = new Object();
private final Object mSPLockLoad = new Object();
public void loadFiles(final Context context, final Locale locale) {
synchronized (mLockLoad) {
//Load SoundPool and other stuff
Thread thread = new Thread() {
@Override
public void run() {
synchronized (mSPLockLoad) {
loadAllSounds(context);
mSPLockLoad.notify();
}
}
};
thread.start();
}
}
然后从一个Activity类我用它来调用它:
public static void loadAudioFiles(final Context context, final Locale locale) {
new Thread(new Runnable() {
@Override
public void run() {
AudioManager.INSTANCE.loadFiles(
context.getApplicationContext(),
locale);
}
}, "AudioManagerInitializeThread").start();
}
在某些时候发生竞争条件并且loadFiles()
被调用两次。问题出在哪里?
如果我在主UI线程上获取实例,我会避免它:
public static void loadAudioFiles(final Context context, final Locale locale) {
AudioManager manager = AudioManager.INSTANCE;
new Thread(new Runnable() {
@Override
public void run() {
manager.loadFiles(context.getApplicationContext(), locale);
}
}, "AudioManagerInitializeThread").start();
}