我有一个基于 Java 的应用程序 (Android),我希望能够在后台执行潜在的长时间操作。AsyncTask 上的 Android 文档建议不要将它们用于可能运行超过几秒钟的任务(为什么会这样?)所以我改用 Java 线程的子类。这个 Thread 子类(HPHeadThread)的目标主要是承载一些异步控制机制的实例,并为这些机制提供访问器方法供其他线程使用。我的目标是能够从引用 HPCHeadThread 的任何线程调用 hHPHeadThread.doStuff(),并让在 HPCHeadThread 中实例化的控制对象在 HPCHeadThread 线程上工作,并且仅在该线程上工作。当没有被其他线程访问时,HPCHeadThread 应该休眠,以免浪费 CPU 周期。
测试活动.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..
}
}
现在,如果我从我的主 TestActivity 线程中调用 hHPHeadThread.doStuff(),工作进程是在 HPCHeadThread 上还是在主 TestActivity 线程上?TestActivity 是否等待 doStuff() 方法返回,然后在其自己的线程中继续顺序执行?方法调用是否会唤醒 HPCHeadThread 和/或它们是否会导致在 HPCHeadThread 的 run() 方法的 while 循环中引发 InterruptedException?