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 have to delete it in some way?
There are two concepts here. One is the thread itself, the thing running in the processor, that has stack memory. The other is the Thread
object, which is basically a control panel to access the thread.
The thread has stack memory which is released when the thread dies (run()
completes or an exception is thrown, basically). However, the Thread
java object stays around until there is no longer a 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
which holds a reference to a Thread
you create. When the start
method is called, your thread is called and it allocates quite a bit of memory for the variable takeUpSomeMemory
. Once the run()
method dies by completing execution or throwing an exception the memory for takeUpSomeMemory
is garbage collected. The memory for this.myThread
is retained until the instanceVariable is set to nil or the object of the enclosing class is garbage collected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With