在 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()。
以上就是关于“在Android线程中如何使用wait”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm