zoukankan      html  css  js  c++  java
  • Object not locked by thread before notify() in onPostExecute

    Asked 5 years, 4 months ago
    Viewed 56k time
    41

    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()

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

    2 Answers

    81
     

    The .notify() method has to be called from within a synchronized context, ie from inside a synchronized block.

    The java.lang.IllegalMonitorStateException is 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;

    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;

     
     
    2

    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 line of both snippets):

    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 ;-)
    }
    
     
     
     
     
    https://stackoverflow.com/questions/24185921/object-not-locked-by-thread-before-notify-in-onpostexecute
  • 相关阅读:
    Solr多核的配置
    Solr开发参考文档(转)
    Solr使用solr4J操作索引库
    Solr和IK分词器的整合
    Solr与mmseg4J的整合
    Lucene实例教程
    Lucene简介
    PHP实现大文件的上传设置
    图片上传预览功能实现
    Logstash 安装和使用
  • 原文地址:https://www.cnblogs.com/pengmn/p/11658507.html
Copyright © 2011-2022 走看看