When a program starts it's an empty room before a party. Then Alice comes in with her tote bag and starts cleaning things up. After some time, Alice rings Bob up and later Bob comes to help Alice in the kitchen. Alice and Bob prepare some sweets, and after a while Steve and Sarah knock at the door with some beer and chips.
Alice, Bob, Steve and Sarah are threads. Alice is the main thread because she organized the party. Sweets, beer and chips are the objects. Note that Steve brought the chips, but Alice can eat them, too! Sarah was responsible for the beers, but others can certainly drink. It doesn't matter who (which thread) brought what (created object) to the party: memory is shared among threds.
Now, let's examine how your Alice works. The main thread of an Android application is an event loop, that can be seen as:
while (running) {
if (input != null) dispatch(input);
sleepForSomeTime();
}
The call to dispatch()
will finally reach your listeners code, so that it's executed on the same thread that handles the touch event. It doesn't matter who created the objects, who registered the listeners and so on.
I think it's not the case for your application, but one may actually need to process events in a pool of background threads. This is accomplished by giving your threads a queue of tasks to be done, and by having your event-driven code update that queue (or you can use the executors framework in java.util.concurrent
)
As a note, you should not start threads inside your constructors because
- some objects may be seen before they are fully constructed (if you use an inner class or an anonymous one)
- the purpose of a constructor is to initialize fields. The creation of a background thread should be handled by the user of the newly constructed object