Using wait in AsyncTask

前端 未结 6 1541
逝去的感伤
逝去的感伤 2021-02-01 01:15

When using a wait in an AsyncTask, I get ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thr

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 02:02

    You have this way to work with asyntask and wait();

    public class yourAsynctask extends AsyncTask {
        public boolean inWait;
        public boolean stopWork; 
    
        @Override
        protected void onPreExecute() {
            inWait = false;
            stopWork = false;
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            synchronized (this) {
                while(true) {
                    if(stopWork) return null;
                    if(youHaveWork) {
                        //make some
                    } else {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
            return null;
        }
    
        public void mynotify() {
            synchronized (this) {
                if(inWait) {
                    notify();
                    inWait = false;
                }
            }
        }
    
        public void setStopWork() {
            synchronized (this) {
                stopWork = false;
                if(inWait) {
                    notify();
                    inWait = false;
                }
            }
        }
    }
    

提交回复
热议问题