Travis Frazier
Travis Frazier

Reputation: 441

Android - do threads stop on their own?

I've been looking around and I really haven't found an answer to this. I know it's good practice to stop the threads yourself, but I've been wondering what happens when I forget to stop them. If I create a new thread and have it run some task, what happens to the thread when the task is completed? For example what happens to the thread in this case:

Thread t = new Thread(new Runnable(){

        public void run() {
            for (int i = 0;i<10;i++){
                foo;
            }
        }
    });
t.start();

Does thread t stop automatically, does it just keep eating up resources, or does it do something else?

Upvotes: 3

Views: 1922

Answers (3)

Phil
Phil

Reputation: 14651

If not a daemon, it won't consume all the resources upon the completion of the task.

Upvotes: 0

Vetsin
Vetsin

Reputation: 2592

The thread will stop when the end of the run method is completed. In your example this would be after 10 iterations of the for loop, assuming foo did not block. If there are no more references to this thread it will then be garbage collected by the JVM.

Upvotes: 5

Sean Owen
Sean Owen

Reputation: 66886

When run() completes, the thread finishes, yes. It is not good practice to stop() a Thread, if that's what you mean.

Upvotes: 2

Related Questions