views:

285

answers:

1

Hi,

I've more than one Handlers in an Activity. I create all the handlers in the onCreate() of the main activity. My understanding is the handleMessage() method of each handler will never be called at the same time because all messages are put in the same queue (the Activity thread MessageQueue). Therefore, they will be executed in the order in which are put into the Queue. They will also be executed in the main activity thread. Is this correct ?

 public void onCreate() {

this.handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {

                            //operation 1 : some operation with instanceVariable1
super.handleMessage(msg);
}
};

this.handler2 = new Handler() {

@Override
public void handleMessage(Message msg) {
                            //Operation 2: some operation with instanceVariable1
super.handleMessage(msg);
}

};

this.handler3 = new Handler() {
@Override
public void handleMessage(Message msg) {
                            //Operation 3: some operation with instanceVariable1
super.handleMessage(msg);

}
};
}
A: 

From the docs "When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue."

So you're right, they will run in the order that you queue them on the UI thread (since you are going to create them in onCreate).

Brandon
Thanks ! So, I don't have to `synchronize` operations to an instance variable of the activity. However, I still have to `synchronize` if _another_ thread is accessing on the instance variable.
Soumya Simanta