Search code examples
androidmultithreadinghandlerandroid-runonuithread

Call Thread.wait()


I need to make currentThread wait when do some operations in UiThread and then in UiThread call currentThread().notify() . I was trying this code

Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
     @Override
     public void run() {
         try {
             currentThread().wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
        AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
        facultyChooser.setTitle("choose")
                .setCancelable(false)
                .setItems(arr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        currentThread().notify();
                    }
                })
                 .create()
                 .show();
         }
     });
}

but got java.lang.IllegalMonitorStateException: object not locked by thread before wait() exception. Please help me.


Solution

  • Try this code:

    final Thread CURRENT_THREAD = currentThread();
    Handler uiHandler = new Handler(Looper.getMainLooper());
    uiHandler.post(new Runnable() {
         @Override
         public void run() {
            AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
            facultyChooser.setTitle("choose")
                    .setCancelable(false)
                    .setItems(arr, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            synchronized(CURRENT_THREAD) {
                                CURRENT_THREAD.notify();
                            }
                        }
                    })
                     .create()
                     .show();
             }
         });
    }
    synchronized(CURRENT_THREAD) {
          try {
              CURRENT_THREAD.notify();
          } catch (InterruptedException e) {
                e.printStackTrace();
          }
    }