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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24185921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:40:36  来源:igfitidea点击:

Object not locked by thread before notify() in onPostExecute

javaandroidmultithreading

提问by Erkan Erol

I try to notify adapters of listviews of main class in onPostExecute but I receive the error: java.lang.IllegalMonitorStateException:object not locked by thread before notify()

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

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

采纳答案by Rudi Kershaw

The .notify()method has to be called from within a synchronizedcontext, ie from inside a synchronizedblock.

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

The java.lang.IllegalMonitorStateExceptionis thrown when you call .notify()on an object that is not used as the lock for the synchronized block in which you call notify. For example, the following works;

java.lang.IllegalMonitorStateException当您调用.notify()未用作您调用通知的同步块的锁的对象时,将抛出。例如,以下作品;

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

But this will throw the exception;

但这会抛出异常;

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

Reference;

参考;

回答by Martin Pfeffer

I had the same error, but (for me) the answer suggested by Rudi Kershaw wasn't the issue... I called the notify()of a Notification the wrong way (see the last lineof both snippets):

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

Not working:

不工作:

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
}

Working:

在职的:

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 ;-)
}