简体   繁体   English

Android中的UI线程和工作线程之间的区别?

[英]Difference between UI Thread and Worker Thread in Android?

I have read documents about Thread on Android, but I could not find differences between UI thread and Worker Thread. 我已经阅读了有关Android上线程的文档,但我找不到UI线程和工作线程之间的差异。 Can someone just give me more example about it? 有人可以给我更多关于它的例子吗?

The Ui thread is the thread that makes any changes required for the ui. Ui线程是进行ui所需的任何更改的线程。

A worker thread is just another thread where you can do processing that you dont want to interupt any changes happening on the ui thread 工作线程只是另一个线程,您可以在其中进行处理,您不希望中断ui线程上发生的任何更改

If you are doing large amounts of processing on the ui thread while a change to the ui is happening the ui will freeze until what ever you have running complete. 如果你正在对ui线程进行大量处理,而ui的更改正在发生,ui将会冻结,直到你运行完毕。

It's partly terminology. 这是部分术语。 People use the word "worker" when they mean a thread that does not own or interact with UI. 当人们指的是不拥有UI或与UI交互的线程时,人们使用“worker”这个词。 Threads that do handle UI are called "UI" threads. 处理UI的线程称为“UI”线程。 Usually, your main (primary) thread will be the thread that owns and manages UI. 通常,您的主(主)线程将是拥有和管理UI的线程。 And then you start one or more worker threads that do specific tasks. 然后启动一个或多个执行特定任务的工作线程。 These worker threads do not modify the UI directly. 这些工作线程不直接修改UI。

for example, if we need to change UI component like change text in Text View, show toast etc , show alert then we need to use UI thread bcoz thread is just process 例如,如果我们需要更改UI组件,如在文本视图中更改文本,显示吐司等,显示警报,那么我们需要使用UI线程bcoz线程只是进程

we can access UI in thread using runOnUiThread method 我们可以使用runOnUiThread方法访问线程中的UI

example of runOnUiThread: use this method inside thread runOnUiThread的示例:在线程内使用此方法

new Thread() {
        @Override
        public void run() {
            //If there are stories, add them to the table
            try {
                     // code runs in a thread
                     YourActivity.this.runOnUiThread(new Runnable() {
                         @Override
                         public void run() {
                             Toast.makeText(context,"this is UI thread",0).show();
                         }
                    });
               } catch (final Exception ex) {
                   Log.i("---","Exception in thread");
               }
        }
 }.start();

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

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