I need to delete streams in Android

I have the following function call from a thread:

        Thread Move = new Thread(){
            public void run()
            {
                while(ButtonDown){
                    UpdateValues();
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Move.start();

      

Will Android delete the thread when the while loop breaks, or do I need to delete it somehow?

+3


source to share


2 answers


When you return from the thread, you essentially stopped it, so no, you don't have to do anything to remove the thread. Please keep in mind that this is not very convenient for streaming in Android. If you update the UI from a non-UI thread, you will most likely get a complaint about you. Instead, you should read a few guides on AsyncTask and move on to this model, as this will allow you to update the interface.



+2


source


There are two concepts here. One of them is the thread itself running in the processor, which has stack memory. The other is an object Thread

, which is basically a control panel for accessing a stream.

There is stack memory in a thread that is freed when the thread dies ( run()

exits or throws an exception, mostly). However, the java object Thread

stays around until there is no more reference to it.

So let's say you had this:



this.myThread = new Thread(){
            public void run()
            {
                int[] takeUpSomeMemory = new int[10000];

                while(ButtonDown){
                    UpdateValues();
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
this.myThread.start();

      

So, you have an instance variable myThread

that contains a reference to the created one Thread

. When the method start

is called, your thread is called and allocates quite a lot of memory for the variable takeUpSomeMemory

. As soon as the method run()

dies, completing execution or throwing an exception, the memory for takeUpSomeMemory

is garbage collected.
Memory for this.myThread

persists until instanceVariable is set to nil or the include class object is garbage collected.

+2


source







All Articles