对象未在onPostExecute中的notify()之前被线程锁定

时间:2014-06-12 13:38:46

标签: java android multithreading

我尝试在onPostExecute中通知适配器的主类列表视图,但是我收到错误:java.lang.IllegalMonitorStateException:对象在notify()之前没有被线程锁定

@Override
protected void onPostExecute(String result) {
    popularfragment.adapter.notifyDataSetChanged();
    recentfragment.adapter.notifyDataSetChanged();
} 

2 个答案:

答案 0 :(得分:77)

.notify()方法必须在synchronized上下文中调用,即从synchronized块内调用。

当您在未用作调用notify的同步块的锁定的对象上调用.notify()时,将引发java.lang.IllegalMonitorStateException。例如,以下工作;

synchronized(obj){
    obj.notify();
}

但这会抛出异常;

synchronized(obj){
    // notify() is being called here when the thread and 
    // synchronized block does not own the lock on the object.
    anotherObj.notify();        
}

参考;

答案 1 :(得分:2)

我有同样的错误,但(对我而言)Rudi Kershaw建议的答案不是问题......我以错误的方式调用notify()通知(参见两个片段的最后一行

无效:

public void update() {
    mBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setPriority(AesPrefs.getInt(R.string.PRIORITY_NOTIFICATION_BATTERY, NotificationCompat.PRIORITY_MAX))
            .setOngoing(true);
    mBuilder.setWhen(AesPrefs.getLong(Loader.gStr(R.string.LAST_FIRED_BATTERY_NOTIFICATION) + Const.START_CLIPBOARD_NOTIFICATION_DELAYED, -1));
    mManager.notify(); // <- lil' mistake
}

<强>工作:

public void update() {
    mBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setPriority(AesPrefs.getInt(R.string.PRIORITY_NOTIFICATION_BATTERY, NotificationCompat.PRIORITY_MAX))
            .setOngoing(true);
    mBuilder.setWhen(AesPrefs.getLong(Loader.gStr(R.string.LAST_FIRED_BATTERY_NOTIFICATION) + Const.START_CLIPBOARD_NOTIFICATION_DELAYED, -1));
    mManager.notify(Const.NOTIFICATION_CLIPBOARD, mBuilder.build()); // <- ok ;-)
}