简体   繁体   English

Android上的runOnUiThread()和无限循环

[英]runOnUiThread() and infinite loop on Android

I do not understand the behaviour of my code. 我不了解我的代码的行为。 To summarize, I have an editText (variable hours in my code) that start with "00". 总而言之,我有一个以“ 00”开头的editText(代码中的可变小时数)。 I am creating a thread which prevents this editText to not have 2 digit. 我正在创建一个线程,以防止此editText没有2位数字。 Let s assume that this editText cannot have more than 2 digits. 假设此editText的位数不能超过2位。 What I am doing is that I create a thread. 我正在做的是创建一个线程。 In this thread, whenever this editText does not have 2 digits(so 1 digit), I add to it a "0". 在此线程中,只要此editText没有2位数字(即1位数字),我都会在其中添加“ 0”。

However, whenever I just put one digit on the editText, it is getting crazy and go into an infinite loop and other stuff that I don't understand. 但是,每当我在editText上放一个数字时,它就会变得疯狂并陷入无限循环和其他我不理解的东西。 Here is my code: 这是我的代码:

Thread digitLessThanTwoThread;
EditText hours = (EditText) findViewById(R.id.hours);
digitLessThanTwoThread= new Thread(){
            @Override
            public void run()
            {
                while(true) {
                    if (hours.getText().toString().length() != 2 && !hours.isFocused()) {
                        main_activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hours.setText("0" + hours.getText().toString());
                            }
                        });
                    }
                }
            }
        };
        digitLessThanTwoThread.start();

Moreover, at the end, The editText hours displayed "00". 此外,最后,editText小时显示为“ 00”。 I also get a message "suspending all threads took: XXX seconds" before doing anything actually! 在实际执行任何操作之前,我还会收到一条消息:“暂停所有线程:XXX秒”!

There are two problems here. 这里有两个问题。 First, the simple one: 首先,简单的一个:

while(true)

This will run the thread at full power until as you seem to be noticing, the OS steps in to stop the runaway thread. 这将使线程全力运行,直到您似乎注意到,操作系统介入以停止失控线程。 You should instead add an addTextChangedListener() listener, for example. 例如,您应该添加一个addTextChangedListener()侦听器。

The more complex one is: 比较复杂的是:

main_activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        hours.setText("0" + hours.getText().toString());
    }
});

I think you are assuming that this is executed synchronously, that is the setText() is executed before runOnUiThread() returns. 我认为您假设这是同步执行的,即setText()是在runOnUiThread()返回之前执行的。 However, it is asynchronous, so next time round the loop your if is still true, and you queue another action on the UI thread to set the text and so on, so the UI thread may never get a chance to run until the OS steps in to halt the runaway thread. 但是,它是异步的,因此下次在循环中您的if是否仍然为true,并且您在UI线程上排队另一个操作以设置文本,依此类推,因此UI线程可能永远不会有机会运行直到操作系统执行操作进入以阻止失控的线程。

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

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