Stochelo Stochelo - 6 months ago 16
Java Question

New thread multiple times

I want to run a thread when I press a button

public void ButtonClick(){

Thread thread = new Thread(){
public void run(){
Log.i("Test", "I'm in thread");
}
};
thread.start();
}


My question is : I want to click several times on this button. Are several thread still existing after the message "I'm in thread" is printed? Or each time the run function is finished, the thread is destroyed?

In case I create several threads which are running at the same time, how can I close them in a clean way?

Thanks for your help!

Answer

Are several thread still existing after the message "I'm in thread" is printed?

No. Each of them will be destroyed automatically.

In case I create several threads which are running at the same time, how can I close them in a clean way?

No need to stop threads, they will be destroyed automatically once they finish their task(execution of run).

To handle the concurrency and safety you should look in to java.util.concurrent which is utility framework for handling concurrency in java.