我在服务中初始化了新的线程,但是当我开始服务时,新的线程就创建了,它使我的应用程序崩溃,因为我在其中使用了摄像头。 如何让它成为该线程的唯一一个实例?
线程何时关闭?如果我在创建它的地方关闭服务,它也会关闭吗?
最佳答案
你可以使用锁或静态变量:
private static boolean isThreadRunning;
然后在您的服务中:
if(isThreadRunning)
return;
Thread t=new Thread(new Runnable(){
protected void run(){
isThreadRunning=true;
while(yourcondition){
//your thread code...
}
isThreadRunning=false;
//if you want to start another thread after this one is ended, you should post a message to a handler here and it should start another thread like this
}
});
关于android - 服务中只有一个 Thread 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784024/