0

我需要在调用currentThread中进行一些操作时等待。我正在尝试这段代码UiThreadUiThreadcurrentThread().notify()

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

但有java.lang.IllegalMonitorStateException: object not locked by thread before wait()例外。请帮我。

4

1 回答 1

1

试试这个代码:

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();
      }
}
于 2014-11-06T14:59:25.450 回答