简体   繁体   English

Android ::在执行主线程中的其他任务之前,阻塞主线程以使工作线程完成

[英]Android:: Blocking main thread for worker thread to finish before executing other tasks in main thread

I am executing some task in the UI thread and created a worker thread that does the networking stuff for me. 我正在UI线程中执行一些任务,并创建了一个工作线程来为我做网络工作。 However, I have something important that needs to be executed once the worker thread finishes. 但是,一旦工作线程完成,我有一些重要的事情需要执行。 Could anybody please suggest me a solution? 有人可以建议我解决办法吗?

{
    Main thread...
    worker thread created..and executed..
    //I need to wait here for the worker thread to finish//
    some useful task to be done
}

Thanks in advance! 提前致谢!

You need to do things on the UI thread after worker has finished? 工作人员完成后,需要在UI线程上执行操作吗? Use runOnUiThread at the end of your worker or use AsyncTask with onPostExecute() . 在工作程序末尾使用runOnUiThread ,或将AsyncTaskonPostExecute() Blocking the UI thread while worker is running doesn't make any sense. 在worker运行时阻止UI线程没有任何意义。

You don't. 你不知道 Blocking the UI thread violates the key rule of threading in Android. 阻止UI线程违反了Android中线程化的关键规则。 Doing so can cause those annoying "Application not responding" dialogs, along with other problems. 这样做可能导致那些令人讨厌的“应用程序不响应”对话框,以及其他问题。

From the Processes and Threads page of the developer docs: 在开发人员文档的“ 进程和线程”页面中:

So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. 因此,您一定不能从辅助线程中操作UI,而必须从UI线程中对用户界面进行所有操作。 Thus, there are simply two rules to Android's single thread model: 因此,Android的单线程模型只有两个规则:

Do not block the UI thread 不要阻塞UI线程

Do not access the Android UI toolkit from outside the UI thread 不要从UI线程外部访问Android UI工具包

You should explore other solutions to what you need to accomplish. 您应该针对需要完成的工作探索其他解决方案。 You need not give specifics on your problem, but ekholm's solution could work, as could simply calling a method in your Activity from the worker thread. 您无需提供有关问题的详细信息,但是ekholm的解决方案可以起作用,就像可以从worker线程简单地在Activity中调用方法一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM