Java Android线程,同一个线程工作两次
在我的应用程序中,我有一个计时器和停止/启动按钮。计时器与线程一起工作 当我点击按钮时,我的计时器开始工作。当我点击stop和start时,我的线程就像两个并行线程一样工作。 如何停止第一个线程并创建第二个线程? 这是密码Java Android线程,同一个线程工作两次,java,android,Java,Android,在我的应用程序中,我有一个计时器和停止/启动按钮。计时器与线程一起工作 当我点击按钮时,我的计时器开始工作。当我点击stop和start时,我的线程就像两个并行线程一样工作。 如何停止第一个线程并创建第二个线程? 这是密码 timer = new Thread(new Runnable() { @Override public void run() { final bo
timer = new Thread(new Runnable() {
@Override
public void run() {
final boolean cont = mSharedPreferences.getBoolean("continuesMode", false);
final boolean statemant = !stopedAlgo && !mUserStop;
if(!statemant){
timerMinutes = 0;
timerHours = 0;
}
while(statemant){
time="";
if(timerMinutes>=60){
timerMinutes = 0;
timerHours++;
}
if(timerHours<10)
time = "0" + String.valueOf(timerHours)+":";
else
time = String.valueOf(timerHours)+":";
if(timerMinutes<10)
time += "0" + String.valueOf(timerMinutes);
else
time += String.valueOf(timerMinutes);
HeadSense.this.runOnUiThread(new Runnable(){
public void run(){
boolean state = mContinuousMode && !stopedAlgo && !mUserStop ;
if(!stopedAlgo && cont){
mTfsValue.setText(time);
timerMinutes++;
}
else{
timerMinutes = 0;
timerHours = 0;
}
}
});
try {
Thread.sleep(1*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
timer.start();
timer=new线程(new Runnable()){
@凌驾
公开募捐{
final boolean cont=mSharedPreferences.getBoolean(“continuesMode”,false);
最终布尔语句=!stopedAlgo&&!mUserStop;
如果(!statemant){
timerMinutes=0;
timerHours=0;
}
while(statemant){
时间=”;
如果(时间长度>=60){
timerMinutes=0;
timerHours++;
}
如果(timerHours据我所知,您的第一个线程(或第二个线程)永远不会因为以下行而停止:
final boolean statemant = !stopedAlgo && !mUserStop;
这是最终结果,将只计算一次,并且永远不会更改。如果在创建线程时将其求值为true
,它将保持为true并继续运行。您需要在此处将布尔语句声明为volatile
。这样做的目的是向编译器提示某些优化可以执行由于此变量由外部线程修改,因此不能使用
此外,您会对以下内容感兴趣-