Reputation: 153
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!
Upvotes: 5
Views: 1728
Reputation: 38910
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:
Upvotes: 2
Reputation: 44
create a class implementing Runnable instead of Anonymous thread ... pass runnable object creating as many threads as you likeSince creating Anonymous Runnable object creates only one object thus limiting you to achieve your requirements. Check the thread status before creating another or create a thread group (depreciated) or a thread pool using concurrency you use callable instead of runnable and pass it to thread pool of definite size or you could convert runnable to callable and then pass it to the pool as many times as you like
class Thop implements Runnable
{
public void run()
{
// operation
}
}
Upvotes: 0
Reputation: 22972
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.
Upvotes: 8