调用Thread.wait()

时间:2014-11-06 14:13:21

标签: android multithreading handler android-runonuithread

我需要在currentThread中执行某些操作然后在UiThread调用UiThread时等待currentThread().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()例外。请帮帮我。

1 个答案:

答案 0 :(得分: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();
      }
}