在AsyncTask中使用wait

jul*_*jul 44 android wait android-asynctask

当我使用a waitAsyncTask,我得到了ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()

是否有可能使用Asynctask等待?怎么样?

谢谢

class WaitSplash extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        try {
            wait(MIN_SPLASH_DURATION);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }       

    protected void onPostExecute() {
        waitSplashFinished = true;
        finished();
    }
}  
Run Code Online (Sandbox Code Playgroud)

Flo*_*Flo 93

使用Thread.sleep()而不是wait().

  • 如果AsyncTask被取消,Thread.sleep()应抛出InterruptedException. (7认同)
  • 这不会阻止所有其他也使用 AsyncTask 运行东西的东西(在蜂窝之后),因为它使用相同的线程? (3认同)

小智 27

您可以使用Thread.sleep方法

    try {
        Thread.sleep(1000);         
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

@Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try {
                Thread.currentThread();
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

        }
Run Code Online (Sandbox Code Playgroud)