1

OK, I have a question regarding handler.

Scenario: Handler mHandler, Runnable mRunnable, int mState.

mRunnable is supposed to to something according to the 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.

Suppose for the sake of argument that mState is initially 1 and will change to 2 after 2.5 seconds.

My question is: Which function will be executed? firstCase() or 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 :)

Behnam
  • 6,510
  • 6
  • 35
  • 65

1 Answers1

0

secondCase(); will be executed.

(In fact, it may be meaningful to declare mState as volatile.)

to execute 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;
            }
        }

};
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127