UI线程与使用处理程序的其他线程之间的通信 [英] Communication between UI thread and other threads using handler

查看:113
本文介绍了UI线程与使用处理程序的其他线程之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在UI线程和后台线程之间进行线程间通信?我想在这里使用通用处理程序概念来更新我的UI. 我有以下概念

How to do inter thread communication between UI thread and background thread? I want use common handler concept here to update my UI. I have the concept as below

new Thread(new Runnable() {
         public void run() {
             while (mProgressStatus < 100) {
                 mProgressStatus = doWork();

                 // Update the progress bar
                 mHandler.post(new Runnable() {
                     public void run() {
                         mProgress.setProgress(mProgressStatus);
                     }
                 });
             }
         }
     }).start();

我想使用两个类,一个类包含主线程,另一个类包含后台线程,并且它们使用相同的处理程序.我该如何执行呢? 我知道这很普遍,但我发现很难准确实施.

I want to use two classes, one class contains main thread, another class contains background thread and they use the same handler. How do I implement this? I know it is very common but I am finding it difficult to exactly implement.

推荐答案

如果不想使用静态概念,则可以传递参数中的任何内容.在下面的代码中,我实现了两个类.如您所问,我在两个线程类中都使用了公共处理程序.我将处理程序h1作为Runnable对象的参数传递,并在其中传递start()方法来触发另一个线程类的run()方法.包含run()方法的线程是UI(主)线程.我们必须使用UI线程来更新UI.工作者(背景)线程无法执行UI更新.工人与UI之间的通信是通过处理程序完成的.因此,我在UI线程类中定义了处理程序h2.当从后台线程类调用UI线程类构造函数时,我从h1获得了来自构造函数的h2值.我使用h2进行交流.实际上,h2和h1属于系统中的相同存储空间.

You can pass anything from the parameters if you don't want to use static concepts. In the below codes, I have implemented two classes. As you asked, I used the common handler in both thread classes. I pass handler h1 as the parameters of Runnable object and start() method there to trigger the run() method of another thread class. The thread which contains run() method is the UI (Main) thread. We must use UI thread to update UI. Worker (Background) threads can't do UI update. The communication between worker with UI is done via handler. So, I define handler h2 in UI thread class. When UI thread class constructor is called from background thread class, I get my h2 values from h1 that come from the constructor. And I use h2 for my the communication. In fact, h2 and h1 belong to the same memory space in the system.

我在以下两节课中进行了讲授,并进行了线程交流,供您参考.

I made below two classes and did thread communication for your reference.

头等舱

 public class MainActivity extends AppCompatActivity {
    Handler h1;
    Thread t;
    EditText editText;
    private Bundle bb = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);

        h1 = new Handler(Looper.getMainLooper()) {

            @Override
            public void handleMessage(Message msg) {
                bb = msg.getData();
                String str = bb.getString("udd");
                editText.setText(str);
                System.out.println(str);
            }
        };
        t = new Thread(new MyRunnable(h1)); //I pass Runnable object in thread so that the code inside the run() method
        //of Runnable object gets executed when I start my thread here. But the code executes in new thread
        t.start(); //thread started

        try {
            t.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}

第二堂课

public class MyRunnable implements Runnable {
    private Handler h2;
    public MyRunnable(Handler h) {
        this.h2 = h;
    }

    @Override
    public void run() {

        //everything inside rum method executes in new thread
        for(int i=0;i<10;i++) {
            Message m = Message.obtain(); //get null message
            Bundle b = new Bundle();
            b.putString("udd", "daju");
            m.setData(b);
            //use the handler to send message
            h2.sendMessage(m);

        }
    }
}

注意:当thread.start()发生时,它将触发Runnable类的运行,并创建一个单独的线程.因此,每次调用start()时,都会有一个与被调用线程具有相同优先级的新线程.

Note: when thread.start() happens, it triggers the run of the Runnable class, it creates a separate thread. So every time, you call start(), there is a new thread with the same priority of callee thread.

希望,这对您有所帮助.

Hope, this helped you.

这篇关于UI线程与使用处理程序的其他线程之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆