阅读量:114
在 Android 中,我们不能直接在非 UI 线程(例如后台线程)中使用 wait() 和 notify() 或 notifyAll() 方法
-
使用
runOnUiThread:在你的后台线程中,将需要更新的 UI 操作包装到
runOnUiThread方法中。这将确保操作在主线程(UI 线程)上执行。new Thread(new Runnable() { @Override public void run() { // 执行耗时任务 final String result = doSomeLongRunningTask(); // 在主线程中更新 UI runOnUiThread(new Runnable() { @Override public void run() { updateUI(result); } }); } }).start(); -
使用
Handler:创建一个
Handler实例并将其关联到主线程的Looper。然后,在后台线程中使用Handler的post方法来执行 UI 更新操作。private Handler mHandler = new Handler(Looper.getMainLooper()); new Thread(new Runnable() { @Override public void run() { // 执行耗时任务 final String result = doSomeLongRunningTask(); // 在主线程中更新 UI mHandler.post(new Runnable() { @Override public void run() { updateUI(result); } }); } }).start(); -
使用
AsyncTask:AsyncTask是一个轻量级的异步类,允许你在后台线程中执行操作,然后在主线程中更新 UI。这是实现此功能的推荐方法。new AsyncTask() { @Override protected String doInBackground(Void... voids) { // 执行耗时任务 return doSomeLongRunningTask(); } @Override protected void onPostExecute(String result) { // 在主线程中更新 UI updateUI(result); } }.execute();
请注意,wait() 和 notify() 或 notifyAll() 是 Java 的内置方法,它们主要用于协调多个线程之间的操作。在 Android 开发中,我们通常使用上述方法来处理线程间的通信和 UI 更新,而不是直接使用 wait()。