My doubt is regarding how to run a piece of code within an API in my service, on another thread.
I have an API func in my service. Only a part of this API's code, which is independent (2-3 LOC), I want to move it to separate thread, as these take up siginificant time, and as these lines of code have no impact on UI thread as of now. This is what I did.
ORIGINAL CODE:
func(){
subA();
subB();
subC();
}
MODIFIED CODE:
Thread mThread = null;
func(){
subA();
if(mThread == null){
mThread = new Thread(){
public void run(){
subB();
subC();
}
}
}
mThread.start();
}
On running this code, I am getting an exception for "thread already started".
I did read on SO about this, that an already started thread cannot be re-started again. I need to create a new thread again and start that. But I do not want to create a new thread object everytime, as that will lead to performance issues on UI thread. Is there any other way this can be handled.
I discovered a couple of other ways to acheive this in android, like Handler, HandlerThread, AsyncTask, etc. But I am not able to settle my mind on which is the best to use here (I do not want to create new objects everytime (of thread/asynctask/handler/handlerthread
), just wan to create thread object once and re-use it everytime).
If anybody has worked on this area before, please help !