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 your case, you are creating many threads since a Thread is created for every button click.
The life span of Thread is over after completion of last statement in run()
method. After execution of run()
method, the thread will enter into TERMINATED
State and it can't be re-run.
Better solution is not creating a new Thread for every button click. If you need more Threads in your application, go for a pool of Threads.
Java provides Executor framework for this purpose. It manages Thread life cycle in better way.
Use one of APIs, which will return ExecutorService
from Executors
e.g. newFixedThreadPool(4)
Have a look at this post and this article for more options.
In case I create several threads which are running at the same time, how can I close them in a clean way?
You can shutdown the ExecutorService
as quoted in below SE post:
How to properly shutdown java ExecutorService
Since you are using Android, you have one more good alternative for multithreading : HandlerThread and Handler
Refer to below post for more details:
Android: Toast in a thread