简体   繁体   English

Android处理程序:延迟后的变量状态

[英]Android handler: state of variables in postdelayed

OK, I have a question regarding handler. 好吧,我有一个关于处理程序的问题。

Scenario: Handler mHandler, Runnable mRunnable, int mState. 场景:处理程序mHandler,Runnable mRunnable,int mState。

mRunnable is supposed to to something according to the mState. mRunnable应该根据mState执行某些操作。

Runnable mRunnable = new Runnable() {

@Override
        public void run() {

            switch (mState) {
            case 1:
                            firstCase();

                break;
            case 2:
                            secondCase();

                break;

            default:
                break;
            }
        }

};

Now I'll issue mHandler.postDelayed(mRunnable, 3000) command. 现在,我将发出mHandler.postDelayed(mRunnable,3000)命令。

Suppose for the sake of argument that mState is initially 1 and will change to 2 after 2.5 seconds. 出于争论的原因,假设mState最初为1,并且在2.5秒后将变为2。

My question is: Which function will be executed? 我的问题是:将执行哪个功能? firstCase() or secondCase() firstCase()或secondCase()

I know you may answer try it yourself, but my true intention of asking this question is to learn about the reason behind this behavior. 我知道您可以自己回答,但是提出这个问题的真正目的是了解这种行为的原因。

Thanks Guys :) 多谢你们 :)

secondCase(); will be executed. 将被执行。

(In fact, it may be meaningful to declare mState as volatile.) (实际上,将mState声明为volatile 可能是有意义的。)

to execute firstCase() : 执行firstCase()

// in a method
final int fState = mState;
Runnable mRunnable = new Runnable() {

@Override
        public void run() {

            switch (fState) {
            case 1:
                            firstCase();

                break;
            case 2:
                            secondCase();

                break;

            default:
                break;
            }
        }

};

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

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