Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
Travis Frazier Avatar asked Feb 25 '26 11:02

Travis Frazier


2 Answers

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.

like image 104
Vetsin Avatar answered Feb 27 '26 02:02

Vetsin


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

like image 26
Sean Owen Avatar answered Feb 27 '26 02:02

Sean Owen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!