I have a Java-based app (Android) and I'd like to be able to perform potentially long operations in the background. The Android docs on AsyncTask advise against using them for tasks that may run for more than a few seconds (why is this?) so I'm using a subclass of Java's Thread instead. The goal of this Thread subclass (HPCHeadThread) is mainly to host the instances of a few asynchronous control mechanisms, and provide accessor methods to said mechanisms for other threads to use. The workflow I'm aiming for is to be able to call hHPCHeadThread.doStuff() from any thread with a reference to HPCHeadThread, and have the control objects instantiated in HPCHeadThread do work on the HPCHeadThread thread and only on that thread. When not being accessed by another thread, HPCHeadThread should sleep so as not to waste CPU cycles. I launch the peripheral thread HPCHeadThread from the main thread (TestActivity) like so:
TestActivity.java
//..snip
private HPCHeadThread hHPCHeadThread;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//...snip
//Create and start our HPCHeadThread
hHPCHeadThread = HPCHeadThread.getHPCThreadHead();
hHPCHeadThread.start();
//..snip
}
HPCHeadThread.java
//..snip
public class HPCHeadThread extends Thread {
private static volatile HPCHeadThread instance;
private static boolean bIsActive = true;
private HPCHeadThread(){
super();
}
public static HPCHeadThread getHPCThreadHead(){
if(instance == null && bIsActive){
instance = new HPCHeadThread();
}
return instance;
}
public void safeStop(){
instance = null;
bIsActive = false;
}
@Override
public void run(){
Thread thisThread = Thread.currentThread();
Thread.currentThread().setName("HPC_Head_Thread");
while(instance == thisThread){
//Our HPCHeadThread 'main' loop
//Try to have it sleep whenever it isn't being used
//Hopefully it will wake nicely upon attempted access,
//perform the desired function, and then return to sleep
try{
Thread.sleep(10000);
}
catch (InterruptedException e){
//e.printStackTrace();
}
}//End while
}//End Run()
public void doStuff(){
//..snip stuff..
}
}
Now if I invoke hHPCHeadThread.doStuff() from within my main TestActivity thread, does the work process on HPCHeadThread or on the main TestActivity thread? Does TestActivity wait for the doStuff() method to return before continuing sequential execution within its own thread? Do method invocations wake HPCHeadThread and/or do they cause an InterruptedException to be thrown in HPCHeadThread's run() method while loop?