views:

74

answers:

2

I can create a class which extends Thread and overrides the run method with a loop. I then start it with myThread.start(), which create the OS thread and executes my run(). That's all good.

However, I don't quite understand the details. I'll have a go at working this out using test code when I get the chance, but before then can anyone answer these:

Q1. When does the constructor get executed, presumably when myThread is declared, or on start()?

Q2. What happens when my run() code completes? Is there a way of getting it to run again in the same thread (i.e. not losing all the thread variable values defined in class) Presumably calling start() might create a new os thread?

Q3. Presumably just calling myThread.run() would execute my run() in the context of the current activity, not mythread, in which case how could it access the thread variables?)

-Frink

+4  A: 

A1) When you construct the instance of your MyThread class

A2) Threads cannot be run twice or restarted, as stated in the documentation.

A3) Yes, calling run() directly will execute that function in the current Thread, not in a new Thread. It doesn't make much sense to create a class that extends Thread if you want to just call run(). You should always call start().

tim_yates
Emphasizing #3: you should *always* call start(). If you don't, the Thread object gets leaked, because it's linked into the ThreadGroup list when it's created and not unlinked until it terminates.
fadden
A: 

Dealing with multythreading and android sdk you should have a look at aysnctask. Because using the class thread or the interface runnable your code becomes more complicated and more difficult to read. It becomes even worse when you implement complex operations that require frequent UI updates.

The goal of AsyncTask is to take care of thread management for you. Have a look at this threading in android

ArtWorkAD